Dmitry Shvedov
Dmitry Shvedov

Reputation: 3286

Make a div, containing an img draggable

I'm trying to make a div draggable. The div contains an img and some text that serves as a label for the image. The problem is that when I start the drag by clicking on the img, the img gets dragged, and not the parent div. How do I fix that?

<div className="container-selected" id={id} draggable="true" onDragStart={this.dragStart} onDragEnd={this.drop} onClick={this.click}>
  <img src={imgSrc} />
  <span className="item-id">Some text</span>
</div>

Here's the CSS:

.container-selected {
  padding: 10px;
  position: relative;
  z-index: 0;

  img {
    width: 3em;
    z-index: -1;
  }

  .item-id {
    position: absolute;
    left: 0;
    top:  53px;
    width: 100%;
    text-align: center;
  }
}

Upvotes: 4

Views: 4446

Answers (2)

Roobie Nuby
Roobie Nuby

Reputation: 1439

This is many years later, but I ran into the same problem, and finally figured it out.

An image is draggable by default, so when you drag an image in a div, the image gets dragged. All you have to do is the make the image non-draggable by:

<img draggable="false" src={status} />

Now when you drag the div, the div and its contained image are dragged together.

Upvotes: 9

Adam Buchanan Smith
Adam Buchanan Smith

Reputation: 9439

You can use HTML5's drag and drop like this: https://jsfiddle.net/bv5fLrth/23/

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div> 

<div id="drag1" draggable="true" ondragstart="drag(event)">

<img id="drag1" src="http://lorempixel.com/400/200/" />
</div>
<script>
  function allowDrop(ev) {
    ev.preventDefault();
  }

  function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
  }

  function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));
  }

</script>

Upvotes: 0

Related Questions