Skip to content
Related Articles

Related Articles

Improve Article

How to dragleave fired when hovering a child element in HTML 5?

  • Last Updated : 08 Mar, 2021
Geek Week

When a div is made draggable and we hover over a div that executes dragenter and dragleave command, we face a problem when there is a child present inside that div which executes the dragleave command as shown below.

Example 1: Here when hovered over child color disappears.

HTML




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0" />
    <script src=
    </script>
  </head>
  <style>
    .yellow {
      background-color: yellow;
    }
  </style>
  <body>
    <div id="drag" draggable="true">Drag me</div>
    <hr />
  
    <div id="drop">
      Drop here
  
      <p>Child Element</p>
    </div>
    <script>
      $("#drop").bind({
        dragenter: function () {
          $(this).addClass("yellow");
        },
  
        dragleave: function () {
          $(this).removeClass("yellow");
        },
      });
  
      $("#drag").bind({
        dragstart: function (e) {
          e.allowedEffect = "copy";
          e.setData("text/plain", "test");
        },
      });
    </script>
  </body>
</html>

Output: As we can see that when hovered over the child element, the dragleave function executes, and thus the color disappears.

Example 2: To overcome this problem we use a counter which executes the dragleave function only when the counter becomes zero. Here when hovered over child color does not disappear



Javascript




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0" />
    <script src=
    </script>
  
  </head>
  <style>
    .yellow {
      background-color: yellow;
    }
  </style>
  <body>
    <div id="drag" draggable="true">Drag me</div>
    <hr />
  
    <div id="drop">
      Drop here
  
      <p>Child Elements</p>
    </div>
    <script>
      var counter = 0;
  
      $("#drop").bind({
        dragenter: function (ev) {
          ev.preventDefault();
          counter++;
          $(this).addClass("yellow");
        },
  
        dragleave: function () {
          counter--;
          if (counter === 0) {
            $(this).removeClass("yellow");
          }
        },
      });
  
      $("#drag").bind({
        dragstart: function (e) {
          e.allowedEffect = "copy";
          e.setData("text/plain", "test");
        },
      });
    </script>
  </body>
</html>

Output:

Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :