6

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.

zjabbari
  • 63
  • 1
  • 6

1 Answers1

3

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));
malinkody
  • 529
  • 4
  • 11
  • Thanks! this worked really nicely. I made some minor changes to code [fiddle](https://jsfiddle.net/vh8cr2tg/4/) to remove the event handler on window, but that's more of a personal preference. – zjabbari Apr 06 '16 at 00:09
  • you should probably add a on mouse leave listener and also set the parent drag to true, so if a user clicks on the nested element and drags out the mouse while its clicked, the draggable attribute wont stay false – akiva Dec 11 '20 at 07:33