javascript – How to prevent a click on a link/anchor or element with a tied event

Question:

In the case of a link:

<a href="http://www.google.com">Google</a>

or in the case of another element that has an event tied to addEventListener , what alternatives are there to prevent the content from being "clicked" and that triggering an action such as following a link, opening a select or another action configured by javascript?

Answer:

One variant is via CSS, using pointer-events .

I discovered this way just this week. Hence the post here.

So using pointer-events: none; mouse clicks will be ignored. This alternative is +/- recent and is supported in HTML elements by more modern browsers (IE11+, Firefox 3.6+, Chrome 2.0+, Safari 4+).

Example
adding and removing a class with this pointer-events: none;

Apart from this CSS method which is the cleanest, you can achieve the same effect using Javascript:

In the case of an <a> , <select> tag and other tags that have a predefined behavior for when they receive a click, it is necessary to add/tie an event handler to be able to cancel/stop the click.

Via javascript there are some alternatives. Using .preventDefault() which as the English name implies prevents the default behavior.

Example:

elemento.addEventListener('click', function(event){
    event.preventDefault();
});

Another option is to prevent the click with javascript by creating a variable to intercept or not the event:

Thus, the variable is first defined and then a check of the state/value of the variable is placed inside the function called by the click:

var bloqueado = true;
// dentro da função chamada pelo evento `click`
if (bloqueado) return false;

Example

Another option is to remove the tied event. Note that this option does not apply to tags like <a> , <select> and others that have a default/native behavior when clicked.

You can also use a DOM element to block the click.

One last option suggested here is to lock this element with another element. Using the z-index is possible to superimpose another element, in this case transparent so that the user is not aware of it (and without spoiling the layout) to superimpose this element that you want to "protect" from clicks, or other interaction. Note that this option prevents, for example, from selecting text and other events in elements that may be visible, thus making them inaccessible to the user.

Example

Scroll to Top