简体   繁体   中英

Applying jquery plugin/function with options on dynamically added elements

In jQuery there is a feature to use $(document).on(...) to assign a event also to the newly added elements in the html for example after ajax request.

Can you give an example of using this with a custom defined function/plugin for example hoverpulse .

Other issue I am facing is that it is also expecting some values to be passed to that function which is returned by hoverpulse while calling it on the selector.

  $(document).ready(function(){  
    $('div.thumb img').hoverpulse({ size: 40, speed: 400 });   
  });

How to pass the options of such function through on() method of jQuery? Note that the options are not to be passed to the handler but the function hoverpulse itself.

The .on() method is used to assign event handlers, it doesn't make sense to be thinking about using it to apply a plugin.

"If I just use $(selector).hoverpulse() will it reassign the same function...therefore executing the effect twice in some case?"

Yes, if you use the same selector it will apply the plugin to all of the elements that match the selector at that time, including elements that were already done earlier. For some plugins that might not matter much, but for others it will. I'm not familiar with .hoverpulse() specifically, but conceivably it might execute the effect multiple times on the same element if you called .hoverpulse() multiple times for that element.

The first workaround that comes to mind is to add a class to elements that have already had the plugin applied, then next time limit yourself to elements that don't have that class:

$('div.thumb img').not(".HPapplied")
                  .hoverpulse({ size: 40, speed: 400 })
                  .addClass("HPapplied"‌​);

Given that you (presumably) need to apply the same options both in document ready and in your Ajax success callback you might like to put the above statement into a function and then call that function from both places. That way if you need to change one of the options you only have to change it in one place.

hi when u dynamically add images, just do it in a way they have an onload event like this...

<div style="position: relative;" class="thumb"><img onload="$(this).hoverpulse();"style="position: absolute; top: 0px; left: 0px;" src="hoverpulse_files/beach1.jpg" height="64" width="64"></div>

it works fine without any other changes in code...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM