Search code examples
javascriptdraggable

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>

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>