Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add CSS class to an element while dragging over w/ jQuery

Is it possible to add a CSS class to an element while it is being dragged over a particular area and replace the class once the element is dropped?

I am not looking for this feature everywhere, but only over a particular area.

like image 699
santa Avatar asked Aug 26 '11 14:08

santa


2 Answers

Yep, it's certainly possible. jQuery UI provides some handy options and events to do this.

For starters, the draggable element can always be referred to by the class .ui-draggable-dragging while it's being dragged.

The droppable method then provides an event called over which will execute a function whenever a valid draggable object is hovered over it. So, inside that function we can refer to .ui-draggable-dragging and add a class to it.

Out and drop events are also offered and we can target the draggable element the same way. Here's how it would look:

$("#droppable").droppable({
    // tolerance can be set to 'fit', 'intersect', 'pointer', or 'touch'
    tolerance: 'intersect',
    // Add .hoverClass whenever #draggable is being hovered over #droppable
    over: function(event, ui) {
        $('.ui-draggable-dragging').addClass('hoverClass');
    },
    // Remove .hoverClass whenever #draggable is no longer hovered over #droppable
    out: function(event, ui) {
        $('.ui-draggable-dragging').removeClass('hoverClass');
    },
    // Add .dropClass whenever #draggable is dropped on #droppable
    drop: function(event, ui) {
        $('.ui-draggable-dragging').removeClass('hoverClass').addClass('dropClass');
    }
});

The above code adds a class when #draggable intersects with #droppable and then replaces that class when #draggable is dropped on to #droppable. Additionally, .hoverClass is removed when the two elements no longer intersect. Here is a working example on jsfiddle.

Hope that helps.

like image 185
Colin Brock Avatar answered Oct 17 '22 03:10

Colin Brock


i found interesting to use the prepared ui object provided by the callback so u dont have to make a dom query again. every little performance gain is good especially when using drag & drop ;-) ...

 over: function(e, ui) {
    $(ui.helper[0]).addClass("success");
  }

...

best.

like image 32
user1624605 Avatar answered Oct 17 '22 02:10

user1624605