Jay
Jay

Reputation: 237

How to check if a jQuery UI plugin is attached to an element?

How can I check to see if a jQuery UI plugin is attached to an element? For example, if I load up the .sortable widget, how can its presence be determined?

The purpose behind this question is that I would like the ability to toggle .sortable on elements. With the ability to see that .sortable is present, I could then call .sortable('destroy') to remove it.

Upvotes: 11

Views: 7129

Answers (5)

Yosiet Serga
Yosiet Serga

Reputation: 47

Just call an instance of sortable, if return undefined, then is not loaded

<pre>
if (typeof $("ul.sortable").sortable('instance') != 'undefined') {
    //$.ui.sortable is loaded and called
} else {
    //call sortable
}
</pre>

Upvotes: 0

Raphael Schweikert
Raphael Schweikert

Reputation: 18556

Since jQuery UI 1.8, special selectors are being added to Sizzle for each widget. These are in the form of :ui-widgetname.

To check for the presence of a sortable widget on an element, you can therefore use:

if(element.is(':ui-sortable')) {
    element.sortable('destroy');
}

Upvotes: 5

Pavdro
Pavdro

Reputation: 427

If anyone is looking for this solution in later jqueryUI versions, the data container's name of sortable plugin is now uiSortable and not sortable. Im using jQueryui 1.10

i.e to find elements u can use

var $elem = $('#sortable-container:data(uiSortable)');

and to find elements that are NOT yet initialized

var $elem = $('#sortable-container:not(:data(uiSortable))');

Upvotes: 2

Corey Hart
Corey Hart

Reputation: 10596

All ui widgets attach their name as true to the element's container data. jqueryui also adds a data filter expression.

var $elem = $('div.sortable-container:data(sortable)');
if ($elem.length){
  // $elem contains list of elements that have sortable widget attached
}

Upvotes: 13

Kevin Peno
Kevin Peno

Reputation: 9196

All UI widgets have are given the class ui-widget. Typically each widget also adds the widget class to the main element. In this case you should see ui-sortable added to the sortable container.

Upvotes: 1

Related Questions