varun teja
varun teja

Reputation: 336

how to create a drag and drop function in html 5?

hi im stuck with making a drag and drop function in html5.i tested the code on chrome and when i try to drop it in the area where i made it for dropping the code
it shows a stop sign as arrow. i actually made a bordered section box in which i have some text that i want to be changed when i drop my image in it.

this is my js code:

function doFirst(){
pic = document.getElementById('pic1');
pic.addEventListener("dragstart", startDrag , false);
left = document.getElementById('left1');
left.addEventListener("dragenter", function(e){e.preventDefault();}, false);
left.addEventListener("dragover", function(e){e.preventDefault();} , false);
left.addEventListener("drop", dropped , false);
}

function startDrag(e){
   var code = '<img id="pic1" src="D:\tuna\11264353_959682364063264_630153199_n.jpg" />';
   e.dataTransfer.setData('hello', code);
}

function dropped(e) {
    e.preventDefault();
    left.innerHTML = e.dataTransfer.getData('hello');
}

window.addEventListener("load", doFirst , false);

Upvotes: 0

Views: 213

Answers (2)

Alvaro Montoro
Alvaro Montoro

Reputation: 29735

First, a piece of advice: learn how to debug and use the developer's tools (specially the console) provided by the modern browsers (or use Firebug/Web development extensions if you prefer).

Had you checked the console, then you'd have seen that the code throws a JS error ("Syntax error: Unexpected token") and you'd know where in the code that error was. In particular, on this line:

var code = '<img id="pic1"  
src="D:\tuna\11264353_959682364063264_630153199_n.jpg" />';

If you search online, you'll see that "javascript strings must be terminated before the next newline character" (from Andrew Dunn's answer to this question). And once that error is fixed:

var code = '<img id="pic1" src="D:\tuna\11264353_959682364063264_630153199_n.jpg" />';

the rest of your code works fine, as you can see on this JSFiddle (I added real URLs to the pictures so you could see the effect working).

Upvotes: 1

Gtito
Gtito

Reputation: 41

try with this code:

<!DOCTYPE HTML>
<html>
    <head>
        <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>
    </head>
<body>

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

    <img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69">

</body>
</html>

Font: http://www.w3schools.com/html/html5_draganddrop.asp

Upvotes: 0

Related Questions