Naomi Naomi - 5 months ago 10
Javascript Question

Multiple draggable with different color depending on which droppable it's in

I have several divs. Some with class eucountry and some with class country. I want the divs with eucountry as class to turn green when it's in the droppable with #EU and red when it's in #not. I want the divs with class country to do the opposite.

Here is my js code

$(document).ready(function() {
$(".eucountry").draggable();


$("#EU").droppable({
drop: function(event, ui) {

$(ui.draggable).css("background-color", "green");
}
});

$("#not").droppable({
drop: function(event, ui) {

$(ui.draggable).css("background-color", "red");
}
});
});


I've tried to use an if statement that :

if($("div").hasClass("eucountry){
$(ui.draggable).css("background-color", "red");
}


but it's not working.Any ideas how I can solve this problem?

Answer

So close, you have just to use the if statement inside drop callback, example :

$("#EU").droppable({
   drop: function(event, ui) {
       if( $(ui.draggable).hasClass("eucountry") ){
           $(ui.draggable).css("background-color", "green"); 
       } 

       if( $(ui.draggable).hasClass("country") ){
           $(ui.draggable).css("background-color", "red"); 
       } 
   }
});

$("#not").droppable({
   drop: function(event, ui) {
       if( $(ui.draggable).hasClass("eucountry") ){
           $(ui.draggable).css("background-color", "red"); 
       } 

       if( $(ui.draggable).hasClass("country") ){
           $(ui.draggable).css("background-color", "green"); 
       } 
   }
});

Hope this helps.