HTML Tutorial

Coming Tutorials

>Home> HTML Tutorial> Dragable Image

HTML Tutorial

Coming Tutorials



To set an image as draggable, initialize the draggable attribute with true.

<img draggable="true">

The HTML5 drag and drop feature allows the user to drag and drop an element to another location. The drop location may be a different application. While dragging an element a translucent representation of the element is follow the mouse pointer.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title> HTML5 Drag & Drop </title> <script type="text/javascript"> function(e) { // Sets the operation allowed for a drag source e.dataTransfer.effectAllowed = "move"; // Sets the value and type of the dragged data e.dataTransfer.setData("Text", e.target.getAttribute("id")); } function dragOver(e) { // Prevent the browser default handling of the data e.preventDefault(); e.stopPropagation(); } function drop(e) { // Cancel this event for everyone else e.stopPropagation() e.preventDefault(); // Retrieve the dragged data by type var data = e.dataTransfer.getData("Text"); // Append image to the drop box e.target.appendChild(document.getElementById(data)); } </script> <style type="text/css"> #dropBox { width: 300px; height: 300px; border: 5px dashed gray; background: lightyellow; text-align: center; margin: 20px 0; color: orange; } #dropBox img { margin: 25px; } </style> </head> <body> <h2>Drag & Drop Demo</h2> <p>Drag and drop the image into the drop box:</p> <div id="dropBox" ondragover="dragOver(event);" ondrop="drop(event);"><!--Dropped image will be inserted here--></div> <img src="../images/kites.jpg" id="dragA" draggable="true" ondragstart="dragStart(event);" width="250" height="250" alt="Flying Kites"> </body> </html>

Share the article to help your friends