I have an elements on page that are draggabe with jQuery. These elements have click event wich navigates to another page (ordinary links for example).
What is the best way to prevent click from firing on dropping such element, while allowing clicking it in not drag and drop state?
I have this problem with sortable elements, but think it is good to have solution for general drag and drop.
I've solved the problem for myself. After that found that same solution exists for Scriptaculous, but maybe someone have a better way to achieve that.
A solution that worked well for me and that doesn't require a timeout: (yes I'm a bit pedantic ;-)
I add a marker class to the element when dragging starts, e.g. 'noclick'. When the element is dropped, the click event is triggered -- more precisely if dragging ends, actually it doesn't have to be dropped onto a valid target. In the click handler, I remove the marker class if present, otherwise the click is handled normally.
Just a little wrinkle to add to the answers given above. I had to make a div that contains a SalesForce element draggable, but the SalesForce element has an onclick action defined in the html through some VisualForce gobbledigook.
Obviously this violates the "define click action after the drag action" rule, so as a workaround I redefined the SalesForce element's action to be triggered "onDblClick", and used this code for the container div:
The parent's click event essentially hides the need to double-click the child element, leaving the user experience intact.
In my case it worked like this:
I had the same problem and tried multiple approaches and none worked for me.
Solution 1
does nothing for me. The item is being clicked after the dragging is done.
Solution 2 (by Tom de Boer)
This works just fine but fails in one case- when I was going fullscreen onclick:
Solution 3 (by Sasha Yanovets)
This does not work for me.
Solution 4- the only one that worked just fine
Yep, that's it- the correct order does the trick- first you need to bind draggable() then click() event. Even when I put fullscreen toggling code in click() event it still didn't go to fullscreen when dragging. Perfect for me!
In jQuery UI, elements being dragged are given the class "ui-draggable-dragging".
We can therefore use this class to determine whether to click or not, just delay the event.
You don't need to use the "start" or "stop" callback functions, simply do:
This is triggered from "mouseup", rather than "mousedown" or "click" - so there's a slight delay, might not be perfect - but it's easier than other solutions suggested here.
I don't really like to use timers or preventing, so what I did is this:
Rocksolid..