Search code examples
javascripthtmldrag-and-drophtml5-draggable

HTML5 Drag and drop. Detecting where element was grabbed


I am working with HTML 5 Drag and Drop API, and implementing sortable list and auto scroll. For some of features, I would like to able to detect which part of element was grabbed

Here is the illustration

enter image description here

Any help would be appreciated, thanks


Solution

  • You can use the computed padding+width of the element and the offsetX property of the MouseEvent to calculate the selected region.

    yourElement.addEventListener('mousedown', function onDragStart(event){
      let width = parseInt(window.getComputedStyle(yourElement).getPropertyValue('width'));
      let padding = parseInt(window.getComputedStyle(yourElement).getPropertyValue('padding-left'));
      let position = event.offsetX;
      let middle = (width / 2) + padding;
    
      if (position <= middle) {
        console.log('left');
      } else {
        console.log('right');
      }
    });
    

    See this jsfiddle for an example: https://jsfiddle.net/c23Lu6gy/28/