Droppable jQuery event does not work

0

I have the following code to do the Drag and Drop event:

$(".device-profiles").draggable({
    revert : true,
    start: function(event, ui) {
        dragColor = $(this).attr("data-color");
        console.log("dragColor: " + $(this).attr("data-color"));
    } 
});

$(".mediaplayer-profiles").droppable({
    drop: function (event, ui){
        $(this).removeClass($(this).attr("data-color"));
        $(this).attr("data-color", ui.draggable.attr("data-color"));
        $(this).addClass($(this).attr("data-color"));
    }
});

The first time I run the drop, it works, but when I try to change it to other places, the effect no longer works.

What could be causing this failure?

    
asked by anonymous 05.09.2014 / 19:14

1 answer

2

You are using the data attribute in the wrong way, although it works that way, there is a specific method .data() which is easier and cleaner to use.

And to use a variable between different functions, you must declare it in global scope first.

Here's an example:

jquery

var dragColor; // declarar a variavel no escopo global

$(".device-profiles").each(function () {
    $(this).addClass($(this).data('color')); // *opcional* colocar o data-color como class em cada elemento
}).draggable({
    revert: true,
    start: function (event, ui) {
        dragColor = $(this).data('color');
        console.log("dragColor: " + dragColor);
    }
});

$(".mediaplayer-profiles").droppable({
    drop: function (event, ui) {
        $(this).removeClass($(this).data('color')).data('color', dragColor).addClass(dragColor);
    }
});

HTML

<div id="draggable">
    <p class="device-profiles" data-color="teste1">Drag me to my target</p>
    <p class="device-profiles" data-color="teste2">Drag me to my target</p>
    <p class="device-profiles" data-color="teste3">Drag me to my target</p>
</div>
<div id="droppable" class="mediaplayer-profiles">
    <p>Drop here</p>
</div>

JSFiddle

    
06.09.2014 / 15:52