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, for example, make an HTTP request.
To add a Handler event is simple, use the 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 previous behaviors to the ones you define. For example:
- When you click on one
<a href="...">
, the browser redirects you to a page
- When you click on the button Submit of a single element
<form>
, an HTTP request will be made
- When you press the arrow key, the browser will make a scroll
All these behaviors are called standard 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? Therein comes the Event.preventDefault()
.
Cancel the event if cancellable, without stopping the spread of the event.
In the quote, it is if cancellable because some browsers do not allow you to override a default behavior. For example: no browser will let you overwrite ALT+F4.
See an example of a checkbox with its superscript 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 e
that you mentioned, is the event
in the functions I mentioned. Every propagated event has an instance of Event
trailer. It is possible to have important information about the event, and functions such as the preventDefault
.
Could you post the code? So it’s easier to understand your question. Advancing the default behavior of a form is Submit,
e.preventDefault();
indicates that you want to prevent default behavior.– Marconi
Marconi actually my doubt is: why in onclick I should put (Event) and in the function I should put (e) to work. For me it was confused because in one I must write "Event" and in the other only "and". But if it got confused I’ll post the code here, it’s that I don’t have much way to post on the forum but I do it haha
– Henrique
Henrique take a tour, you’ll understand how it works around here!
– Marconi