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

21

In the case of a link:

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

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

    
asked by anonymous 23.01.2014 / 17:18

3 answers

20

A variant is via CSS, using pointer-events

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

So using in CSS 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 CSS pointer-events: none;

In addition to this CSS method which is the cleanest, you can get the same effect using Javascript:

In case you are a <a> , <select> tag and other tags that have predefined a behavior for when they are clicked, you must add / bind a event handler to cancel / stop the click.

Via javascript there are some alternatives. Using .preventDefault() as the name in English indicates prevent 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 the event:

So the variable is first defined and then a variable status / value check 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 tethered event. Note that this option does not apply to tags such as <a> , <select> , and others that have a native / predefined behavior when they are clicked.

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

One last suggested option here is to block this element with another element. Using z-index it is possible to override another element, in this case transparent so that the user does not notice (and not ruin the layout) override this element that wants 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 being inaccessible to the user.

Example

    
23.01.2014 / 17:18
8

I usually use the preventDefault event via jQuery. See:

$('.elemento').on('click', function(e) {
    e.preventDefault();
    alert('Você clicou aqui e nada aconteceu!');
});
    
28.01.2014 / 19:54
4

Using pointer-events is a good idea if you do not need to support previous versions of Internet Explorer, which I do not think is the case.

Improving slightly the version of the code posted by thiagonzalez and that works in all browsers is:

$('.elemento').click(function(e){
    e.preventDefault ? e.preventDefault() : e.returnValue = false;
});
    
29.01.2014 / 14:36