Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Drag and drop parent from child element

I have a list of elements and in each element there is a handle control element. I can easily drag and drop the elements to reorder. However I'm unsure to limit the drag start to the handle element.

eg:

<ul>
    <li draggable="true" ondragstart="..." ondrop="..." ondragover="..."><div class="reorder"></div>Item 1</li>
    <li draggable="true" ondragstart="..." ondrop="..." ondragover="..."><div class="reorder"></div>Item 2</li>
    <li draggable="true" ondragstart="..." ondrop="..." ondragover="..."><div class="reorder"></div>Item 3</li>
</ul>

In the above code, I can click and drag on the handle element or the text "Item #" to reorder them.

I thought in the ondragstart function I could check if the class of the event.target is handle and if not do event.preventDefault() but it seems the target is always the li whether the drag starts from the div or li.

So is there a way to check if the mouse was over a child element on the ondragstart event

like image 815
Jonathan. Avatar asked Aug 24 '14 20:08

Jonathan.


1 Answers

Im based on the comments of Mouser. See this example:

var object = document.querySelector('li');

var dragger = document.querySelector('li .reorder');

dragger.addEventListener('mousedown', function () {
  object.setAttribute('draggable','true');
});

dragger.addEventListener('mouseout', function () {
  object.removeAttribute('draggable');
});

http://codepen.io/anon/pen/qOWJYF

like image 126
Alonso Soto Avatar answered Nov 03 '22 19:11

Alonso Soto