Your JavaScript application is reactive to HTML events. That is, when the user clicks a button, you can add a handler to define some behavior when this button is clicked, eg make an HTTP request.
To add an handler event is simple, use addEventListener
:
document.querySelector('#meu-botao').addEventListener('click', function() {
console.log('O botão foi clicado');
});
<button id="meu-botao">Clique-me</button>
Events may have behaviors that are prior to the events you define. For example:
- When you click a
<a href="...">
, the browser redirects you to a page
- When you click the submit button of a
<form>
element, an HTTP request will be made
- When you press the keyboard arrow, the browser will scroll scroll
All of these behaviors are called default behaviors and are defined by the browser.
But what if you want to create a game to run in the browser and need to use the arrows to have another behavior? That's where Event.preventDefault()
comes in.
Cancel the event if it is cancelable, without stopping the propagation of the event.
In the quote, that is if it is cancelable because some browsers do not allow you to override a default behavior. For example, no browser will let you override ALT + F4 .
See an example of a checkbox with its overridden behavior:
let prevent = document.querySelector("#prevent");
let noPrevent = document.querySelector("#no-prevent");
prevent.addEventListener("click", event => {
console.log('clicou!');
event.preventDefault();
});
noPrevent.addEventListener("click", event => {
console.log('clicou!');
});
<input type="checkbox" id="prevent">com preventDefault
<br />
<input type="checkbox" id="no-prevent">sem preventDefault
The% of% you commented on, is e
in the functions I quoted. Every event propagated has an instance of event
trailer. It is possible to have important event information, and functions such as Event
.