Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling jquery methods on dynamically added elements

We can make all elements of class 'button' as JQuery UI Buttons using the following

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

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

How can we achieve that?

like image 586
objects Avatar asked Mar 15 '11 05:03

objects


2 Answers

I'm afraid you'll have to explicitly call the method after the element is added.

e.g If you are adding a button to the div with id xyz then

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

I'm still searching for a better solution , and would post if I find one

like image 157
Clyde Lobo Avatar answered Oct 01 '22 19:10

Clyde Lobo


If you are adding them at a well-defined spot, then 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 addition events:

$(".button").livequery(function() { $(this).button(); });
like image 32
cdmckay Avatar answered Oct 01 '22 18:10

cdmckay