Skip to content
Related Articles

Related Articles

Improve Article
HTML | ondragstart Event Attribute
  • Last Updated : 11 Feb, 2019

HTML ondragstart Event Attribute is used when the user wants to drag the text or element. It is simply the process in which we press on the desired text to drag and drop them to a different location.

Syntax:

    ondragstart="script" 

DRAG & DROP process includes many operation:

  1. Operations used to the draggable target:
    • ondrag-Used when an element is being dragged
    • ondragstart – Used when the user starts to drag an element
    • ondragend – Used when the user has finished dragging the element
  2. Operations used to the drop target:
    • ondrop: Used when the dragged element is dropped on the drop target
    • ondragover: Used when the dragged element is over the drop target
    • ondragleave: Used when the dragged element leaves the drop target
    • ondragenter: Used when the dragged element enters the drop target

Example-1: Return when the element draged and dropped.




<!DOCTYPE HTML>
<html>
  
<head>
    <style>
        .droptarget {
            float: CENTRE;
            width: 150px;
            height: 45px;
            margin: 25px;
            padding: 15px;
            border: 2px solid LIGHTGREEN;
        }
    </style>
</head>
  
<body>
  
    <p>Drag the text between the boxes.</p>
  
    <div class="droptarget" 
         ondrop="drop(event)" 
         ondragover="allowDrop(event)">
        
        <!-- ondragstart script -->
        <p ondragstart="dragStart(event)" 
           ondrag="dragging(event)" 
           draggable="true" 
           id="dragtarget">
          PRESS & DRAG
      </p>
    </div>
  
    <div class="droptarget"
         ondrop="drop(event)"
         ondragover="allowDrop(event)">
  </div>
  
    <p id="demo"></p>
  
    <script>
        function dragStart(event) {
            
            event.dataTransfer.setData(
              "Text", event.target.id);
        }
  
        function dragging(event) {
            
            document.getElementById(
              "demo").innerHTML = "Dragging";
        }
  
        function allowDrop(event) {
            event.preventDefault();
        }
  
        function drop(event) {
            event.preventDefault();
            var data = 
               event.dataTransfer.getData("Text");
            
            event.target.appendChild(
              document.getElementById(data));
            
            document.getElementById(
              "demo").innerHTML = 
              "Dropped";
        }
    </script>
  
</body>
  
</html>

Output:



Before Drag:

After Drop:

Supported Browsers:

  • Chrome 4.0
  • Firefox 3.5
  • Safari 6.0
  • Opera 12.0
  • Internet Explorer 9.0



My Personal Notes arrow_drop_up
Recommended Articles
Page :