Frage

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.

War es hilfreich?

Lösung

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/

Andere Tipps

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);
     }
});
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top