Doubt about events in a Javascript function [duplicate]

1

I'll try to summarize

I was having a problem with an onclick on a button, and can solve using e.preventDefault ();

But the question arose, to function I had to add "and" my function and became function myFunction(e) And in my html code I had to put the onclick that way

onclick="addList(event)"

I tried to search about event and maybe I did not search correctly but I did not find it, I believed that the values in function were optional, but in this case I had a surprise because it only works exactly that way, using (event) in the onclick and (e) in the function.

Can anyone give me a light on this part? I was confused

    
asked by anonymous 09.10.2018 / 02:13

1 answer

3

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 .

    
09.10.2018 / 06:16