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).
We can disable drag and drop on HTML elements by setting the draggable attribute to false . We set draggable to false so we can't drag it. We add event listeners for the dragstart and drop events with addEventListener .
Draggable() Method This method allows the elements to be dragged with the help of mouse. Using jQuery UI, we can make the DOM(Document Object Model) elements to drag anywhere within the view port. This can be done by clicking on the draggable object by mouse and dragging it anywhere within the view port.
$ (selector, context). droppable (options) Method. The droppable (options) method declares that an HTML element can be used as an element in which you can drop other elements. The options parameter is an object that specifies the behavior of the elements involved.
jQuery UI draggable() method is used to make any DOM element draggable. Once the element is made draggable, you can move it by clicking on it with the mouse and drag it anywhere within the viewport.
$('.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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With