I have a question / task that is so obvious that I still wonder why I couldn't find a solution for that...
In a JavaScript application that is using jQuery UI I'm using the draggable()
and droppable()
API to be able to move elements around. This works straight forward and as expected.
But now I want to change the mouse cursor in such a way that it shows where I can drop an element (cursor: "copy"
) or where it's not possible (cursor: "no-drop"
).
This should - of course - only happen during dragging, otherwise the normal cursor should be shown.
Note: it can be assumed that a drop is only allowed in one special <div>
(e.g. identified by an id
or class
) and everywhere else a drop is not allowed.
You can set the cursor style of the draggable to no-drop
while dragging using the start event callback using css()
method, and change it to copy
when it is over a droppable within over
event callback.
Once the draggable leaves droppable, you can revert the cursor back to no-drop
within the out
event callback, and set reset it back to the default cursor when dragging stops by setting the CSS cursor
property value to initial
within the stop event callback of draggable as shown below:
$(function() {
$("#draggable").draggable({
start: function(event,ui){
$(this).css("cursor", "no-drop");
},
stop: function(event,ui){
$(this).css("cursor", "initial");
}
});
$("#droppable").droppable({
over: function(event, ui) {
ui.draggable.css("cursor", "copy");
},
out: function(event, ui) {
ui.draggable.css("cursor", "no-drop");
}
});
});
div {
display: inline-block;
margin: 20px;
text-align: center;
}
#draggable {
width: 50px;
height: 50px;
line-height: 50px;
background: dodgerblue;
}
#droppable {
width: 100px;
height: 100px;
line-height: 100px;
background: hotpink;
}
<link href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<div id="draggable">
<span>Drag</span>
</div>
<div id="droppable">
<span>Drop here</span>
</div>
Ok, thank you very much! All your answers were very helpful and inspired me to a solution that's working for me: http://jsfiddle.net/qck9kf17/
The "trick" is basically:
$('.box').draggable({ cursor: "no-drop" });
$('.container').droppable({
over: function(){
$('body').css('cursor','copy');
},
out: function(){
$('body').css('cursor','no-drop');
}
});
Give the dropzone a class (dropzone
) and when you start dragging add a class to the body element (draggingInEffect
) via Javascript.
Once you stop dragging remove that class from the body again.
Then add a CSS rule body.draggingInEffect .dropzone { cursor: url(whatever); }
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