HTML5 supports drag and drop, that allows user to move a content from one side to another. Here I demonstrate drag and drop a text from one <div>
to another <div>.
please download full script from Download Source Code
below javascript code will do drag drop
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev, ctrl) {
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>
ev.PreventDefault() - will prevent fire default event
ev.dataTransfer.setData("text", ev.target.id) - will set data type and value of dragged data
Below is HTML tag
<h2>Drag and Drop Text</h2>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
<div id="drag001" draggable="true" ondragstart="drag(event, this)" >Drag Item 1</div>
<div id="drag002" draggable="true" ondragstart="drag(event, this)" >Drag Item 2</div>
<div id="drag003" draggable="true" ondragstart="drag(event, this)" >Drag Item 3</div>
</div>
<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
ondrop - event fires when release mouse left button
ondragover - event fires when mouse move over the control/HTML tag
draggable="true" - make the <div> element draggable
ondragstart="drag(event, this)" - fires when user start dragging
finally add below style to <div> tag so that it will show as box
<style>
#div1, #div2 {
float: left;
width: 100px;
height: 75px;
margin: 10px;
padding: 10px;
border: 1px solid black;
}
</style>
No comments:
Post a Comment