jas7457
jas7457

Reputation: 1991

How to drag and drop element into new div using HTML5?

I'm trying to follow the guide here to make drag and drop work for my site, but I'm running across a problem catching the drop event.

Pretty much what I want to do is allow users to drag an element into the div at the bottom, and once they actually drop it in, it will add it to that div.

Here is my fiddle. As you can see, the handleDrop function I created never gets called.

I've also tried to add the eventListener "drop" on the individual elements instead of the one that they will be dropped into, but that doesn't seem to work either. I've commented this out in the fiddle. Any help?

Upvotes: 0

Views: 2628

Answers (1)

Milan and Friends
Milan and Friends

Reputation: 5610

Here's a Fiddle, and another approach.

HTML

<img id="1" src="/" draggable="true" ondragstart="drag(event)" alt="Image 1"/>
<img id="2" src="/" draggable="true" ondragstart="drag(event)" alt="Image 2"/>
<img id="3" src="/" draggable="true" ondragstart="drag(event)" alt="Image 3"/>
<img id="4" src="/" draggable="true" ondragstart="drag(event)" alt="Image 4"/>
<img id="5" src="/" draggable="true" ondragstart="drag(event)" alt="Image 5"/>

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

</div>

CSS

#playlist {
  position: absolute;
  top: 150px;
  left: 0;
  width: 960px;
  min-height:160px;
  background-color:#e5e5e5;
}
#playlist img {
  margin: 5px;
}
img {
  width: 150px;
  height: 90px;
  margin: 5px;
}

JS

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).cloneNode(true));
}

Upvotes: 1

Related Questions