Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a nested element not draggable in a draggable container?

I'm using HTML5 drag and drop on a parent container, but I want to disable the drag effect on some of its children, specifically an input so that users can select/edit input content easily.

Example: https://jsfiddle.net/Luzub54b/

<div class="parent" draggable="true">
   <input class="child" type="text" value="22.99"/>
</div>

Safari seems to do this for inputs by default so try it on Chrome or Firefox.

like image 435
zjabbari Avatar asked Oct 30 '22 08:10

zjabbari


1 Answers

I was looking for something similar and found a possible solution using the mousedown and mouseup events. It's not the most elegant solution but it's the only one that worked consistently for me on both chrome and firefox.

I added some javascript to your fiddle: Fiddle

;
(function($) {

  // DOM Ready
  $(function() {
    $('input').on('mousedown', function(e) {
      e.stopPropagation();
      $('div.parent').attr('draggable', false);
    });

    $(window).on('mouseup', function(e) {
      $('div.parent').attr('draggable', true);
    });

    /**
     * Added the dragstart event handler cause 
     * firefox wouldn't show the effects otherwise
     **/
    $('div.parent').on({
      'dragstart': function(e) {
        e.stopPropagation();
        var dt = e.originalEvent.dataTransfer;
        if (dt) {
          dt.effectAllowed = 'move';
          dt.setData('text/html', '');
        }
      }
    });
  });
}(jQuery));
like image 86
malinkody Avatar answered Nov 14 '22 21:11

malinkody