How to Drag and Drop Images using HTML5 ?
In this article, we will see how to create a drag and drop functionality using HTML5.
Approach: The following approach will be implemented to Drag and Drop Images using HTML5.
Example: In this example, we will see how to drag and drop an image.
HTML
<!DOCTYPE HTML>
< html >
< head >
< title >
How to Drag and Drop Images using HTML5 ?
</ title >
< style >
#div1 {
width: 350px;
height: 70px;
padding: 10px;
border: 1px solid #aaaaaa;
}
</ style >
</ head >
< body >
< p >
Drag the GeeksforGeeks image
into the rectangle:
</ p >
< div id = "div1" ondrop = "drop(event)"
ondragover = "allowDrop(event)" >
</ div >
< br >
< img id = "drag1" src =
draggable = "true" ondragstart = "drag(event)"
width = "336" height = "69" >
< 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 >
</ body >
</ html >
|
Output:
Last Updated :
15 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...