Web Info and IT Lessons Blog...

Thursday 21 May 2015

Html 5 Drag And Drop

This is the first lesson in Html5 lessons series and in this lesson we will learn to add drag and drop feature to an html element.

Html5 Drag and Drop

Drag and drop allows an html element to be dragged from its original and dropped some where else in the web page and it retains its new position. The element that is to be dragged should have the attribute (draggable="true") otherwise it could not be dragged from its place. The next thing we need is a place where we drop the dragged element i.e a div element will work fine. So basically this is how the whole process is going to work:

1. We will make an image draggable by assigning the attribute (draggable=true) to it.
2. Ondragstart event we will call javascript drag() function which will start the data transfer of the image element.
3. We will create two div elements and make both of the divs droppable by calling allowDrop() function ondragover event.
4. When the draggable image is dropped in any of the droppable divs, ondrop event is triggered which calls drop() function.
5. Inside the drop function (ev.dataTransfer.getData) is used to receive the dragged element which is then appended to the element it is dropped inside using (ev.target.appendChild).

Html Code:

<div id="div1" class="box" ondrop="drop(event)" ondragover="allowDrop(event)">
Drag Image Here</div>
<div id="div2" class="box" ondrop="drop(event)" ondragover="allowDrop(event)">
Drag Image Here</div>
<img id="drag1" src="image.jpg" draggable="true" ondragstart="drag(event)" 
width="150" height="150" />

Css Code:

.box{
    border:1px solid black;
    width:160px;
    height:190px;
    float:left;
    margin-right:10px;
    padding:0px;
}

Javascript Code:

<script type="text/javascript">
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>

Demo: Html 5 Drag And Drop

Drag Image Here
Drag Image Here


No comments:

Post a Comment