A variant is via CSS, using Pointer-Events.
I discovered this way only this week. Hence the post here.
Thus 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, one can get the same effect using Javascript:
In case it is a tag <a>
, <select>
and other tags that have predetermined a behavior for when receiving a click you need to add/tie a event handler
to cancel/stop the click.
There are some alternatives via javascript. Using .preventDefault()
that as the English name indicates prevents default behavior.
Example:
elemento.addEventListener('click', function(event){
event.preventDefault();
});
Another option is to prevent javascript clicking 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 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 who have a native/pre-closed behavior when they receive a click.
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 z-index
it is possible to superimpose another element, in this case transparent to without the user noticing (and without spoiling the layout) to superimpose this element that is wanted to "protect" from clicks, or other interaction. Note that this option prevents, for example, selecting text and other events in elements that may be visible, making it inaccessible to the user.
Example
In the case of select, I think it is only possible to prevent it from opening with the Pointer-Events (nice find! ), or overlapping another element. On anchors, a preventDefault() would have the same effect, no?
– bfavaretto
@bfavaretto, yes, also found "a good find". Regarding anchors yes, exact. I didn’t add it to make the answer more complex with alternatives. But I’m actually thinking how to add since there are good people who have valid arguments about preference for
.preventDefault()
instead ofreturn false;
– Sergio