Question

My goal is to make an element draggable using jQuery UI if it has a certain class present. The class is added using toggleClass on dblclick.

Adding the 'draggable' class to the right element on double click:

    $("article.spread").dblclick(function() {
        $(this).toggleClass("draggable");
    });

Then I use this to make the element draggable:

    $( ".draggable" ).draggable();

Only it will not work. The toggleClass is successful but it isn't draggable.

Was it helpful?

Solution

You are adding the class dynamically after the first drggable is fired on your elements and will not live evalueted.

You can add the drggable when you are adding the class and enable/disable it if it's already attached:

$("article.spread").dblclick(function () {
    $(this).toggleClass("draggable");
    if ($(this).data('draggable')) {
        $(this).draggable('option', 'disabled') ? $(this).draggable('enable') : $(this).draggable('disable');
    } else {
        $(this).draggable();
    }
});

Demo: http://jsfiddle.net/IrvinDominin/8J7sq/

OTHER TIPS

It is not working because you are declaring $(".draggable").draggable() and then add class to an element.

$(".draggable").draggable() will only make the current elements on page having draggable class draggable.

you can try something like

$("article.spread").dblclick(function() {
     if ($(this).data('draggable')) {
        $(this).draggable({ cancel: "div" });
        $(this).data('draggable', false);
     }
     else {
        $(this).draggable();
        $(this).data('draggable', true);
     }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top