Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply jQuery UI widgets to ajax loaded elements

I want to activate the jQueryUI button widget on a given selector, lets say '.button'.

Whats the best way to automatically activate the widget on any new '.button' elements inserted to the DOM after the initial page load via ajax.

Previously, I used the livePlugin with code something like this:

$('.button')
    .live(function(){
        $(this).button();
    })

Since 'live' has been moved to the jQuery core the live function requires an event type as the first parameter so this is no longer possible. Is there alternative method within the jQuery core that will achieve this?

like image 663
th3hamburgler Avatar asked Apr 01 '10 11:04

th3hamburgler


1 Answers

You have a few options here. First, there's the liveQuery plugin, like this:

$(.button).liveQuery(function() { $(this).button(); });

Another alternative is to call the selector on your elements when you load them, this for example finds all .button only in the response, so doesn't mess with existing elements before the ajax call:

$.ajax({
   url: 'page.html'
   success: function(data) {
     //stuff...
     $('.button', data).button();
   }
});

Another similar approach if you have a lot going on is to have your plugins in a function like this:

function rigUI(context) {
  $('.button', context).button();
  $('.date', context).datepicker();
}

$(rigUI); // Load at document.ready, default context is document

//in ajax load love above call: rigUI(data);
like image 101
Nick Craver Avatar answered Nov 06 '22 21:11

Nick Craver