Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining If jQuery UI Draggable Is Initialized

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?

like image 328
Fred Chateau Avatar asked Mar 18 '14 11:03

Fred Chateau


People also ask

How do you know if an element is draggable?

Use the draggable attribute to set whether the element is draggable or not. Set it using the values true and false.

Why is draggable not working?

Check whether your draggable object is already loaded in the viewport. If it is not, it won't work properly. JUST AFTER the draggable object to be absolutely sure that everything is loaded at the correct time. When you'll be sure everything is ok, then you'll be able to refactor.

How do I use draggable JS?

By default, only image and text can be draggable. To drag an image, you simply hold the mouse button down and then move it. To drag the text, you need to highlight some text and drag it in the same way as you would drag an image.


2 Answers

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)');
like image 176
rd3n Avatar answered Sep 28 '22 16:09

rd3n


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.

like image 35
maxshuty Avatar answered Sep 28 '22 17:09

maxshuty