Search code examples
javascriptjqueryeventsdrag-and-dropjquery-ui-sortable

Preventing click event with jQuery drag and drop


I have elements on the page which are draggable with jQuery. Do these elements have click event which 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 is not dragged and drop state?

I have this problem with sortable elements but think it is good to have a solution for general drag and drop.

I've solved the problem for myself. After that I found that same solution exists for Scriptaculous, but maybe someone has a better way to achieve that.


Solution

  • Solution is to add click handler that will prevent click to propagate on start of drag. And then remove that handler after drop is performed. The last action should be delayed a bit for click prevention to work.

    Solution for sortable:

    ...
    .sortable({
    ...
            start: function(event, ui) {
                ui.item.bind("click.prevent",
                    function(event) { event.preventDefault(); });
            },
            stop: function(event, ui) {
                setTimeout(function(){ui.item.unbind("click.prevent");}, 300);
            }
    ...
    })
    

    Solution for draggable:

    ...
    .draggable({
    ...
            start: function(event, ui) {
                ui.helper.bind("click.prevent",
                    function(event) { event.preventDefault(); });
            },
            stop: function(event, ui) {
                setTimeout(function(){ui.helper.unbind("click.prevent");}, 300);
            }
    ...
    })