Search code examples
javascriptjquerydragonkeypress

Esc to cancel drag event jquery drag


I am using http://threedubmedia.com/code/event/drag

Sometimes user accidentally starts a drag or for any other reason wants to cancel drag, how can this be achieved?

A standard practice is that user can press esc.

How could we cancel drag with esc press using http://threedubmedia.com/code/event/drag?


Solution

  • You can attach event to the page to listen for Esc key and then manually trigger the dragend event.

    var ESCAPE_KEYCODE = 27;
    var dragEl = $('.draggable').drag(function( ev, dd ){
      // do stuff
    });
    
    $(document).on('keyup', function(e) {
        if (e.keyCode === ESCAPE_KEYCODE) {
             $(dragEl).trigger('dragend');
        }
    });