Search code examples
javascriptcsshtmlhtml5-draggable

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.


Solution

  • 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));