Search code examples
javascripthtmldraggable

Drag the entire parent div with just the handle


I intend to drag the entire parent div with only the handle attached to its left. See below code snippet, the 30x30 image is my drag handle for now:

var DRAG_CLASS = "beingdragged";

div.ondragstart = function() {
  this.classList.add(DRAG_CLASS);
};

div.ondragend = function() {
  this.classList.remove(DRAG_CLASS);
};
img {
  cursor: move;
  float: left;
}

div {
  border: 1px solid red;
  background: lightblue;
  width: 100%;
  transform: 0.5s ease;
}

div.beingdragged {
  width: 95%;
}
<!DOCTYPE html>
<html>
<body>
  <div id="div" draggable="true"><img src="https://placehold.it/30x30">
    <p>this is some text</p>
  </div>
</body>

</html>

I want the entire div to move along with the cursor as the user moves the cursor around, and as one would expect in a drag operation. However, as you can observe in the output, only the image is being dragged, even though I have set draggable="true" to the entire parent div. The entire parent div stays where it was even though the cursor moves around.

I have added a class DRAG_CLASS to the div, so as you can see, the dragstart and the dragend events are firing correctly.

What then is the issue?


Solution

  • Sure the div is draggable, as you can see when you drag it around somewhere other than the image.

    However the image is also, by default, independently draggable. Easy to disable, though, with draggable="false" or the appropriate css rule.

    var DRAG_CLASS = "beingdragged";
    
    div.ondragstart = function() {
      this.classList.add(DRAG_CLASS);
    };
    
    div.ondragend = function() {
      this.classList.remove(DRAG_CLASS);
    };
    img {
      cursor: move;
      float: left;
    }
    
    div {
      border: 1px solid red;
      background: lightblue;
      width: 100%;
      transform: 0.5s ease;
    }
    
    div.beingdragged {
      width: 95%;
    }
    <!DOCTYPE html>
    <html>
    <body>
      <div id="div" draggable="true"><img draggable="false" src="https://placehold.it/30x30">
        <p>this is some text</p>
      </div>
    </body>
    
    </html>