Wednesday, June 11, 2014

How to use drag and drop in a webpage using HTML and JS

HTML5 is the latest  version of HTML it has capability to deliver rich internet applications without using any additional plugins.So we can make hi-end web applications using HTML5.HTML5 is cross-platform so that work with different devices.

This tutorial will teach you how to use drag and drop feature of HTML5 to drag an object (say image) from one place to other in a web page.


Step 1:#createfile

Create the html file.

Open notepad and type the codes as given below:


<!DOCTYPE HTML>
<html>
<head>
<style>
p {font-family: "Times New Roman";font-size: 20px;}
#divbox {width:350px;height:70px;padding:10px;border:5px solid #aaaaaa;}
</style>
<script>
function DropPermission(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>

<p>Drag the helloworld image into the rectangle:</p>

<div id="divbox" ondrop="drop(event)" ondragover="DropPermission(event)"></div>
<br>
<img id="drag1" src="hello.jpg" draggable="true" ondragstart="drag(event)" width="336" height="69">

</body>
</html>

Step 2:#save

Save your notepad file in .html format

Step  3:#execution

Note:HTML5 doesn’t support older browsers.Execute this file in any latest browsers.I here use Google Chrome.

You can see the output as given below






Try to drag the hello world image to the box and see the magic..

#drag




#drop





Have fun...

1 comment:

  1. it`s really nice and interesting blog...we can lend lot from here.

    ReplyDelete