Categories
JavaScript Answers

How to Disable All Mouse Clicks on a Page with JavaScript?

Spread the love

Sometimes, we want to disable all mouse clicks on a page with JavaScript.

In this article, we’ll look at how to disable all mouse clicks on a page with JavaScript.

Disable All Mouse Clicks on a Page with JavaScript

To disable all mouse clicks on a page with JavaScript, we can call stopPropagation , stopImmediatePropagation and preventDefault in the event handler for the click and contextmenu events to disable left and right-click events respectively.

For instance, we can write:

$(document).click((e) => {
  e.stopPropagation();
  e.preventDefault();
  e.stopImmediatePropagation();
  return false;
});

$(document).bind('contextmenu', (e) => {
  e.stopPropagation();
  e.preventDefault();
  e.stopImmediatePropagation();
  return false;
});

We call $(document).click to add a click event handler.

And we call $(document).bind to add an event handler for the contextmenu event.

stopPropagation stops the propagation of the event to the top of the DOM tree.

preventDefault prevents the default action of the events.

And stopImmediatePropagation prevents other listeners of the same event from being called.

Conclusion

To disable all mouse clicks on a page with JavaScript, we can call stopPropagation , stopImmediatePropagation and preventDefault in the event handler for the click and contextmenu events to disable left and right-click events respectively.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *