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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With