Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to listen to dragend event on div

I have a div where I simply want to listen to dragend event but for some reason, it’s not working. I want to console log when the blue box gets dropped inside the rectangle but it’s giving nothing…

Here’s the code:

<!DOCTYPE html>
<html>
  <head>
    <style>
      #a {
        width: 350px;
        height: 70px;
        padding: 10px;
        border: 1px solid #aaaaaa; }
      #drag1 {
        background-color: blue;
        width: 100px;
        height: 70px;
      }
    </style>
  </head>

  <body>
    <p>Drag the blue box into the rectangle and wait for the console log:</p>

    <div id="a"></div>
    <br />
    <div id="drag1" draggable="true"></div>
  </body>

  <script>
    dropArea = document.getElementById("a");
    dragger = document.getElementById("drag1");
    dropArea.addEventListener("dragend", () => {
      console.log("Hello.....");
    });
  </script>
</html>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

dragend event is launch from element drag when you finish to drag it

you have to put the dragend event on drag element and not the drop area

change

dropArea.addEventListener("dragend", () => {

by

dragger.addEventListener("dragend", () => {
    dropArea = document.getElementById("a");
    dragger = document.getElementById("drag1");
    dragger.addEventListener("dragend", () => {
      console.log("Here.....");
    });
<!DOCTYPE html>
<html>
  <head>
    <style>
      #a {
        width: 350px;
        height: 70px;
        padding: 10px;
        border: 1px solid #aaaaaa; }
      #drag1 {
        background-color: blue;
        width: 100px;
        height: 70px;
      }
    </style>
  </head>

  <body>
    <p>Drag the blue box into the rectangle and wait for the console log:</p>

    <div id="a"></div>
    <br />
    <div id="drag1" draggable="true"></div>
  </body>

</html>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading