Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to Drag and Drop Images using HTML5 ?

  • Last Updated : 22 Oct, 2021

In this article, we will see how to create a drag and drop functionality using HTML5. 

Approach:

Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.

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:




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!