11

I have a list of items that have some jQueryUI buttons associated with them. After an action (deleting an item) I want to reload the list via ajax.

Only problem is when I do so the JQueryUI buttons no longer show, just the standard markup.

I know I can use jQuery.live() for dynamically adding click handlers etc, but how do I apply a jQueryUI button() to them?

2 Answers 2

12

When you reload via ajax, call .button() (or whatever variant you're using) in that context, like this:

$.ajax({
  //other options..
  success: function(data) {
    //insert elements
    $(".button", data).button();
  }
});

This will run .button() on elements only in the response (not the others already in the page/DOM elsewhere) with class="button".

You can't really use .live() or anything like that here, that relies on event bubbling, not really anything to do with adding/removing elements...when it comes to plugins you need need to execute them again against the new elements you add. Or, the less efficient but more generic approach would be the .livequery() plugin, used like this:

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

As I said though, it's not the most efficient thing in the world, since it actually monitors the DOM for changes in various ways.

Sign up to request clarification or add additional context in comments.

2 Comments

Cool thanks. So the short answer is - you can't unless you use the livequery plugin. Might check it out anyway but I take your point about efficiency if that's how it works. Useful info about calling methods in context though - I think my main concern was avoiding re-running .button() on all the elements in the page, which you answered.
As side note to this answer, I had to to reverse the order for the "refresh" where it's $(".button", data).button(), I had to do $(data, ".button").button(), just in case someone else is trying and it's not working.
0

You can re-bind the event handler with:

$("#mybutton").unbind().click(function(){ ..do..something... });

1 Comment

Nice thanks - but it's not just the event handler - jqueryui adds markup and other things for each button. otherwise I could just use live for the click handler. I'm trying to avoid using callback JS on top of jQuery.load() if possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.