Tony_Henrich
Tony_Henrich

Reputation: 44085

How to dynamically attach a jQuery plugin to a div?

A user can dynamically create a new div in a web page based on actions like clicking a button. Then based on certain criteria, I would like to attach and execute one of many available jQuery plugins (all already loaded in the page) to the newly created div. How can this be done?

Upvotes: 1

Views: 122

Answers (1)

bitifet
bitifet

Reputation: 3669

Unfortunately there is no creation event you can hear for.

But, if you know which events can trigger the creation of those divs (I suppose you can't modify the actual code which creates them), and only in case that they does'nt stop event propagation, you could hear for the same events and, after a minimal delay (with setTimeout()) to ensure it's actions to pe fully permormed, check for matching divs WHITHOUT a given class. Then apply (or not) propper plugin and add that class to avoid doing it again next time.

This could be something similar to:

$("#myContainer").on("click", "a, button", function(){
    setTimeout(function(){
        $("#myContainer div.someClass").not(".managed").each(function(){
            var me = $(this);
            …
            me.addClass("managed");
    }, 100);
});

Upvotes: 1

Related Questions