Question

Is there a way of testing to determine if a jQuery UI draggable class has been initialized?

I have a series of divs with the class "draggable1".

For reasons beyond the scope of this question, I do not want to initialize the class in advance, rather I need to initialize the class the first time one of the divs is selected, which I do in a click event handler. Then, I assume I don't want to keep re-initializing the class every time another div is selected. So, I need to determine if one of the divs has already been clicked and initializing the draggable is not necessary.

Or am I looking at this incorrectly? Should I simply re-initialize the draggable class every time another div is selected?

Was it helpful?

Solution

Assuming you are using jQuery UI 1.9+ (specify your version if not), you can retrieve your draggable div data to check if draggable is initialized using :

jQuery('.draggable1').data('ui-draggable');

Your click handler function will look like :

$('.draggable1').click(function() {
    var $div = $(this);
    if(!$div.data('ui-draggable'))
        $div.draggable();
});

See it in action in this jsFiddle

Explanation : the jquery UI draggable widget is based on the jQuery UI widget factory and as described in the 'Instance' section of the documentation :

The widget's instance is stored using jQuery.data() with the widget's full name as the key.

You can also use the :data selector to check if your div element already has a draggable widget bound to it :

$div.is(':data(ui-draggable)');

OTHER TIPS

It doesn't need to be so complicated...

Just check using jQuery's hasClass like this:

var isDraggable = $(elem).hasClass("ui-draggable");

if (isDraggable) {
    //do stuff
}

All draggable elements get the ui-draggable class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top