Search code examples
javascriptjquerydrag-and-drop

How to trigger hover when dragging ghost element over?


I'm using HTML5 drag and drop. How do I get the hover event to trigger when the ghost element is being dragged over the div? The below code works if I just move the mouse over, but not when I'm dragging an element over.

$(".droppable").on("mouseover", function (e) {
    e.stopPropagation();
    $(this).addClass('droppable-border');
}).on('mouseout', function (e) {
    $(this).removeClass('droppable-border');
});

Solution

  • Just use the ondragover and ondragleave event attributes

    <!DOCTYPE HTML>
    <html>
    <head>
        <style>
            #droptarget {
                float: left; 
                width: 200px; 
                height: 35px;
                padding: 10px;
                border: 1px solid #aaaaaa;
              }
        </style>
    </head>
    <body>
       <p draggable="true" id="dragtarget">Drag me into the rectangle</p>
    
       <div id="droptarget" ondragover="this.style.backgroundColor = 'green'" ondragleave="this.style.backgroundColor = 'white'"></div>
    </body>
    </html>

    OR You can use jquery

    $('#droptarget').on('dragover',function(){
      this.style.backgroundColor = 'green'
    });
    
    $('#droptarget').on('dragleave',function(){
      this.style.backgroundColor = 'white'
    });
    <!DOCTYPE HTML>
        <html>
        <head>
            <style>
                #droptarget {
                    float: left; 
                    width: 200px; 
                    height: 35px;
                    padding: 10px;
                    border: 1px solid #aaaaaa;
                  }
            </style>
        </head>
        <body>
           <p draggable="true" id="dragtarget">Drag me into the rectangle</p>
    
           <div id="droptarget"></div>
           <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        </body>
        </html>