p3kr1s p3kr1s - 6 months ago 28
HTML Question

removing previous "droppable" jQuery UI

I am new with learning jQuery UI and I am having a bit of trouble.

I am trying to create a droppable element, that can be dropped in divs with a certain class.
I have this working (so it the element will drop in that class), but I would want to "update" the old class, when the element is dropped into a new class.

http://jsfiddle.net/nxkLf1y9/1/
My fiddle shows the example (so it can be dropped in any element with the class "droppable" (to show this, the class will turn green.) When i drop the element into the next class, I want the color of the old class to revert back to normal, and for the new class to be green (where the element currently is sitting.)

so drop the box in the first div, the div will turn green, it won't drop in the 2nd div because it doesn't have the class "droppable", drop it in the 3rd div, and it will turn green, but the first box is still green too.

My js.

jQuery(function() {
jQuery( "#draggable" ).draggable({revert: "invalid"});
jQuery( ".droppable" ).droppable({
drop: function( event, ui ) {
jQuery( this )
.css({backgroundColor:'green'});
jQuery('#draggable').appendTo('#droppable')
}
});
});


Thanks for the help!

Answer

What you can do is use a class instead of inline styles:

Fiddle Example

jQuery(function() {
  jQuery("#draggable").draggable({
    revert: "invalid"
  });
  jQuery(".droppable").droppable({
    drop: function(event, ui) {

      //Remove Class of previous active
      jQuery('.active').removeClass('active');

      //Make this active
      jQuery(this)
        .addClass('active');
      jQuery('#draggable').appendTo('#droppable')
    }
  });
});

CSS

.droppable.active {
  background: green;
}