17
votes

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).

4
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

4 Answers

51
votes
$('.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.

9
votes

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.

3
votes

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.

0
votes

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

jQuery UI Draggable API