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:
- We have given a rectangle area and an image, the task is to drag the image and drop it into the rectangle.
- We have to enable ondrop=”drop(event)” and ondragover=”allowDrop(event)” to make the rectangle for image insertion.
- The image link is inserted in the HTML page using <img> src attribute.
- Whenever we are going to insert the image, we have to enable draggable=”true”. Also, enable ondragstart=”drag(event)” so that this image can be draggable along with setting the image width and height.
Example:
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:
Please Login to comment...