objects
objects

Reputation: 8677

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?

Upvotes: 7

Views: 725

Answers (4)

cdmckay
cdmckay

Reputation: 32240

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(); });

Upvotes: 1

Clyde Lobo
Clyde Lobo

Reputation: 9174

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

Upvotes: 2

cesarsalazar
cesarsalazar

Reputation: 708

What you might want to use is the delegate method. You can find more about it here: http://api.jquery.com/delegate/

$('yourSelector').yourHandler();

becomes

$('yourSelector').delegate('yourHandler');

Upvotes: -1

JohnP
JohnP

Reputation: 50019

You should be able to use livequery to reinitialize your plugin calls : http://brandonaaron.net/code/livequery/docs

Upvotes: 0

Related Questions