Kurkula
Kurkula

Reputation: 6762

Html5 drap and drop issue with displaying ids

I am trying to display id of control which is dragged and dropped using html5. I am trying to figure out where did I do the mistake? This is my fiddle

I am trying to make sure that the control is still in its same place even after dragging and dropping.

<div id="div1" ondrop="drop(event, this)" ondragover="allowDrop(event)"></div>
<br/>
<img id="drag1" src="//placehold.it/336X69/ff0000" draggable="true" ondragstart="drag(event)" width="336" height="69" />
<div>
    <input type="text" id="textbox1" draggable="true">
</div>

JScode

function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData('Text/html', ev.target.id);
}

function drop(ev, target) {
    alert(data)
    ev.preventDefault();
    console.log(target.id, ev.target.id)
    var data = ev.dataTransfer.getData("text/html");    
}

css code

#div1 {
  width: 350px;
  height: 70px;
  padding: 10px;
  border: 1px solid #aaaaaa;
}

Upvotes: 0

Views: 18

Answers (1)

Saar
Saar

Reputation: 2306

Your code is quite ok, the problem is jsFiddle when you set the events on the HTML.

if you set it on the javascript pane it works (small adjustments needed).

Check this fiddle: http://jsfiddle.net/1227vf9t/14/

HTML:

<div id="div1"></div>
<br/>
<img id="drag1" src="//placehold.it/336X69/ff0000" draggable="true" width="336" height="69" />
<div>
    <input type="text" id="textbox1" draggable="true">
</div>

javascript:

   var div1 = document.getElementById("div1");
    var drag1 = document.getElementById("drag1");
    var textbox1 = document.getElementById("textbox1");

    div1.addEventListener("drop",drop,false);
    div1.addEventListener("dragover",allowDrop,false);

    drag1.addEventListener("dragstart",drag,false);

        function allowDrop(ev) {
            ev.preventDefault();
        }

        function drag(ev) {
            console.log("drag", ev);
            ev.dataTransfer.setData('text/html', ev.target.id);
        }

        function drop(ev) {
            console.log("drop",ev);
            ev.preventDefault();
            var data = ev.dataTransfer.getData("text/html");
            textbox1.value = data;
        }

Upvotes: 1

Related Questions