I'm having kind of an issue about a drag & drop system I'm currently developing.
I have a :hover
style on a div the user can drop something on.
It works when I simply hover over it, but not when I am dragging an element.
Is there a workaround to show that style even when dragging?
$(document).on('dragstart','#draggable',function(e){
e.originalEvent.dataTransfer.setData("data",$(this).attr('data-text'));
});
$(document).on('drop','#droppable',function(e){
console.log(e.originalEvent.dataTransfer.getData("data"));
});
$(document).on('dragover','#droppable',function(e){
e.preventDefault();
});
div{
display: inline-block;
width: 100px;
height: 100px;
text-align: center;
line-height: 100px;
font-family: Arial
}
#droppable{
border: 2px solid green;
}
#droppable:hover{
background-color: rgba(0,0,0,0.2);
}
#draggable{
border: 2px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="droppable">Hover me !</div>
<div id="draggable" draggable="true" data-text="I exist too ! :(">Drag me !</div>
If you mouseover an element which is covered by another element, the mouseover event doesn't fire (unless the covering element is a child of the element, in which case it bubbles).
Introduction to JavaScript Drag and Drop API To drag an image, you simply hold the mouse button down and then move it. To drag the text, you need to highlight some text and drag it in the same way as you would drag an image.
Heh, I finally found the events I was looking for, I couldn't find them before :
.on('dragenter') // Triggers when you enter your element
.on('dragleave') // Triggers when you leave your element
Demo:
$(document).on('dragstart','#draggable',function(e){
e.originalEvent.dataTransfer.setData("data",$(this).attr('data-text'));
});
$(document).on('drop','#droppable',function(e){
console.log(e.originalEvent.dataTransfer.getData("data"));
$(this).removeClass('hover');
});
$(document).on('dragenter','#droppable',function(e){
e.preventDefault();
$(this).addClass('hover');
});
$(document).on('dragleave','#droppable',function(e){
$(this).removeClass('hover');
});
div{
display: inline-block;
width: 100px;
height: 100px;
text-align: center;
line-height: 100px;
font-family: Arial
}
#droppable{
border: 2px solid green;
}
#droppable:hover,#droppable.hover{
background-color: rgba(0,0,0,0.2);
}
#draggable{
border: 2px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="droppable">Hover me !</div>
<div id="draggable" draggable="true" data-text="I exist too ! :(">Drag me !</div>
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