17

A have a large div (a map) that is draggable via jQuery UI draggable. The div has child divs which are clickable.

My problem is that if you drag the map, on mouse up, the click event is fired on whatever child div you started the drag from.

How do I stop the mouse up from triggering the click event if its part of a drag (as opposed to someone just clicking without a drag, in which case the click event is desired).

James Tauber
  • 3,386
  • 6
  • 27
  • 37
  • I had the same problem and have found a simple solution. On the child element define `draggable` before `click`, like this: `$('element').draggable({disabled: true});` – cakan Nov 20 '15 at 08:48

4 Answers4

50
$('.selector').draggable({
    stop: function(event, ui) {
        // event.toElement is the element that was responsible
        // for triggering this event. The handle, in case of a draggable.
        $( event.originalEvent.target ).one('click', function(e){ e.stopImmediatePropagation(); } );
    }
});

This works because "one-listeners" are fired before "normal" listeners. So if a one-listener stops propagation, it will never reach your previously set listeners.

Tom de Boer
  • 954
  • 8
  • 8
  • http://jsfiddle.net/qYz9V/2/ here is the fiddle of this answer :) thank you. –  Oct 12 '13 at 22:54
  • 3
    the fiddle shows it's working, but for some reason it doesn't for me... – WtFudgE Apr 30 '14 at 08:06
  • 7
    This solution is not working in FF 31, event.toElement is undefined. However instead of event.toElement use event.originalEvent.target will work in all browsers – Attenzione Jan 21 '15 at 14:07
  • 1
    This doesn't work if the click event is attached to the child. – Sophivorus Aug 13 '16 at 19:12
  • This prevents the next real click to the target. I have to double click for the click to work again. – rzb Feb 23 '17 at 17:41
10

I had this problem and the solution is to apply the draggable event handler BEFORE the click event handler. I was moving some code around and suddenly had this problem. I finally realized I had switched the order in which I applied the handlers. When I switched it back, things started working properly again -- drag did not cause a click.

JohnOpincar
  • 5,620
  • 3
  • 35
  • 38
3

Could you perhaps set a variable such as "justDragged = true" when starting the drag and then on the mouseUp event check this variable and if true, set it to false and then do a event.preventDefault + return w/o doing anything. This way it skips the first click after the drag. Seems kind of hackish, perhaps others will have a more elegant solution.

Klinky
  • 2,084
  • 15
  • 12
0

An alternative is to simply not allow dragging from clickable areas within the draggable:

jQuery UI Draggable API

Ryan
  • 7,499
  • 9
  • 52
  • 61