Tomas M Tomas M - 2 years ago 149
Javascript Question

jQuery disable clicks temporarily

My website has lots of elements which trigger ajax data retrieval on click, and some drag&drop elements handled by jquery ui. Many elements use their own click events, attached directly to them. I need some functionality which will ignore all mouse clicks/mouseup/mousedown events temporarily under some predefined circumstances. For example, I want to disable drag & drop entirely until some ajax request is in progress, etc. I thought I would bind on click and preventDefault(), I tried to bind on document, like this, but it doesn't seem to work:

$(document).on("mousedown", "*", null, function(ev){ev.preventDefault();});

I think it's because when the event reaches $(document), it was already triggered on all childs, so it's too late to preventDefault().

One solution I could imagine is to set some global variable, like ignore_clicks=true; and then add to every function which handles mouse click a check if this variable is true or not. This seems very difficult and I'm afraid even impossible due to external click handlers like in jquery-ui code.

Another solution I imagine is to temporarily put some fixed style element, 100% width and 100% height, zero opacity, over the current page, but this doesn't seem like an ideal solution, feels more like a hack. Furthermore if there is any ongoing animation on the webpage while it is covered by transparent element, the performance of the animation is degraded.

Is there any simple and elegant solution which would allow me to temporarily block all mouse clicks on the given page? (mouseup & mousedown too).

Answer Source

One solution is to stop the event in the capturing phase by using addEventListener:

document.addEventListener("mousedown", function(e) {
}, true /* true == capturing phase */);

Do note that this won't work in IE8.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download