evt argument inside a function in javaScript

Phil Rv picture Phil Rv · Apr 2, 2015 · Viewed 15k times · Source

evt argument inside a function in javaScript

Hello stackoverflow community. I need to know how is the evt argument used in these functions. There are some examples in the internet which have the argument evt inside of a function, but I don't see them using the argument.

document.getElementById("creator").addEventListener("click", function(evt){
    alert("created");
});

document.getElementById("change").addEventListener("click", function(evt){
    alert("changed");
});

I guess the evt argument is just set as undefined because those functions are never called with a value for the argument.

  • So what is the reason for setting the argument variable evt?
  • can it be hello instead of evt?
  • if it is predefined to the event listeners, how can I find a list of predefined arguments?

Answer

rjmacarthy picture rjmacarthy · Apr 2, 2015

When an event is invoked, it will be passed an event object as it's first argument. You can name evt whatever you like. Common names are e evt and event.

I typically use this for things like

event.preventDefault() Stop an events default action, on submit for example.

and

event.target Find the tagret of the element the event was invoked on.

There are a lot more properties that can be used on the event object, and becomes very useful if you know how to use it. More information about event object here.

https://developer.mozilla.org/en/docs/Web/API/Event