Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

disable all click events on page (javascript)

Tags:

Whats the easiest way to temporarily disable all mouse click/drag etc events through javascript?

I thought I could do document.onclick = function() { return false; }; ...etc, but that's not working.

like image 639
fearofawhackplanet Avatar asked Nov 18 '09 13:11

fearofawhackplanet


People also ask

How do I turn off page click?

Dynamically disable all clicks on pagelet freezeClic = false; // just modify that variable to disable all clics events document. addEventListener("click", e => { if (freezeClic) { e. stopPropagation(); e. preventDefault(); } }, true);

How do I restrict click events?

You can't prevent click with css, you must use javascript. The dislpay:none only hide a element, in this case, a div.


1 Answers

If the objective is to disable click on the whole page then you can do something like this

document.addEventListener("click", handler, true);
    
function handler(e) {
  e.stopPropagation();
  e.preventDefault();
}

true argument in addEventListener would ensure that the handler is executed on the event capturing phase i.e a click on any element would first be captured on the document and the listener for document's click event would be executed first before listener for any other element. The trick here is to stop the event from further propagation to the elements below thus ending the dispatch process to make sure that the event doesn't reach the target.

Also you need to stop default behavior associated with event target elements explicitly as they would be executed by default after the dispatch process has finished even if the event was stopped propagating further from above

It can be further modified to use selectively.

function handler(e) {
  if(e.target.className=="class_name"){
    e.stopPropagation();
    e.preventDefault();
  }
}

handler modified this way would disable clicks only on elements with class "class_name".

function handler(e) {
  if(e.target.className!=="class_name") {
    e.stopPropagation()
  }
}

this would enable clicks only on elements with class "class_name". Hope this helped :)

like image 176
Sid Avatar answered Oct 22 '22 09:10

Sid