Drag detection

Drag detection

This is a very simple example that allows HTML elements to be moved using the mouse. In order to make any visible element draggable, add the draggable=”true” attribute to any visible HTML5 element. Notice that some elements are draggable by default, such as <img> elements. In order to detect a drag, add an event listener for the

In order to detect a drag, add an event listener for the dragstart event:

  1. <ol ondragstart=dragStartHandler(event)>
  2.    <li draggable=“true” data-value=“fruit-apple”>Apples</li>
  3.    <li draggable=“true” data-value=“fruit-orange”>Oranges</li>
  4.    <li draggable=“true” data-value=“fruit-pear”>Pears</li>
  5. </ol>

In the above code, we made all of the <li> elements draggable, and we detect a dragstart event occurring to any item within the ordered list: <ol ondragstart=”dragStarthandler(event)”>.

When you put an ondragstart handler on an element, each of its draggable children could fire the event! It’s a sort of “inheritance of handlers”… In the above example, the handler is declared at the <ol> level, so any subordinate <li> element will fire the event.

Try the following interactive example in your browser (just click and drag one of the list items) or play with it at CodePen.

Screenshot:

drag n drop fruits

Complete code from the example:

  1. <!DOCTYPE html>
  2. <html lang=“en”>
  3. <head>
  4.    
  5.      function dragStartHandler(event) {
  6.          alert(‘dragstart event, target: ‘ + event.target.innerHTML);
  7.      }
  8.    
  9. </head>
  10. <body>
  11.   <p>What fruits do you like? Try to drag an element!</p>
  12.   <ol ondragstart=dragStartHandler(event)>
  13.       <li draggable=“true” data-value=“fruit-apple”>Apples</li>
  14.       <li draggable=“true” data-value=“fruit-orange”>Oranges</li>
  15.       <li draggable=“true” data-value=“fruit-pear”>Pears</li>
  16.   </ol>
  17. <p>Drop your favorite fruits below:</p>
  18.  <body>
  19. <html>

In this script, the event handler will only display an alert showing the name of the target element that launched the event. 

https://codepen.io/w3devcampus/embed/MaWKZb?user=w3devcampus&default-tab=result&slug-hash=MaWKZb&theme-id=0&height=496&name=cp_embed_1

Leave a comment