You can intercept the click event before it reaches the button, run the tests you need, and decide whether to let the event reach the button or not.
To do this you will need to understand how events propagate through the DOM, this answer has a more complete explanation, but a summary would be:
- The user clicks on the button
- The event
click
propagation of the window
up to the button
. (Capture Phase)
- The event arrives at
button
. (Target Phase)
- The "pimple" event back to
window
. (Bubbling Phase)
Maybe it will be easier to understand with the image below:
That said, you could hear the event click
in the father of button
in the capture phase (Capture Phase) and choose whether or not to allow the event to propagate to the button
.
To do this just use the method Element.addEventListener()
with the parameter useCapture
as true
so that the Handler run in Capture Phase.
btnParent.addEventListener('click', meuHandler, true);
Within meuHandler
you can prevent the event from reaching the button using the method Event.stopPropagation()
.
An example of the concepts explained below:
var btn = document.getElementById('btn')
var check = document.getElementById('check')
var wrapper = document.getElementById('wrapper')
btn.addEventListener('click', function () {
console.log('-> Esta função sai da página!')
})
wrapper.addEventListener('click', function(event) {
if (check.checked) {
console.log('Evento de click cancelado...')
event.stopPropagation()
}
}, true)
<span id="wrapper">
<button id="btn">Click</button>
</span>
<label>
<input id="check" type="checkbox"> Cancelar envio
</label>
Luiz, did any of the answers solve your problem? If yes, you can choose the one that best solved and accept it, see here how and why to do it. It is not mandatory, but it is a good practice of the site, to indicate to future visitors that it solved the problem. And when I get 15 points you can also vote in all the answers you found useful :-) And if none answered/solved, you can comment and/or if applicable, [Edit] the question with more details :-)
– hkotsubo