Call jquery methods for dynamically added elements

We can make all the elements of the class 'button' as jQuery user interface buttons using the following

$('.button').button(); 

But what if we also wanted any future elements to be added to the UI Buttons as well.

How can we achieve this?

+7
source share
4 answers

I'm afraid you will have to explicitly call the method after adding the element.

For example, if you add a button to a div with id xyz , then

$("#xyz").append(" <button>").button();

I'm still looking for a better solution and send a message if I find one

+2
source

If you add them to a clearly defined place, you can just do something like:

 var newButton = $("<input>", { type: "button" }); $("body").append(newButton); newButton.button(); 

Or you can use the LiveQuery plugin (as suggested by JohnP) and listen for DOM adding events:

 $(".button").livequery(function() { $(this).button(); }); 
+1
source

You can use livequery to reinitialize your plugin connections: http://brandonaaron.net/code/livequery/docs

0
source

What you can use is the delegate method. You can learn more about this here: http://api.jquery.com/delegate/

 $('yourSelector').yourHandler(); 

becomes

 $('yourSelector').delegate('yourHandler'); 
-one
source

All Articles