Trigger :hover selector when dragging

Zenoo picture Zenoo · Nov 27, 2017 · Viewed 12.6k times · Source

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?

Answer

Zenoo picture Zenoo · Nov 27, 2017

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>