By John McCollum


2018-10-11 14:04:42 8 Comments

Consider the following snippet of code:

document.querySelector("input").addEventListener("input", function(event){
    document.querySelector("p").textContent = event.target.value;
});

If I remove the event parameter, the code still works as expected:

document.querySelector("input").addEventListener("input", function(){
    document.querySelector("p").textContent = event.target.value;
});

But how? My best guess is that it is somehow available through lexical scope in addEventListener, but I'm not sure. Can anyone confirm?

JSFiddle

1 comments

@Quentin 2018-10-11 14:07:57

See MDN:

The read-only Window property event returns the Event which is currently being handled by the site's code. Outside the context of an event handler, the value is always undefined.

You should avoid using this property in new code, and should instead use the Event passed into the event handler function. This property is not universally supported and even when supported introduces potential fragility to your code.


My best guess is that it is somehow available through lexical scope in addEventListener, but I'm not sure.

It is a global: window.event. It just happens to exist only while an event is being processed.

Compatibility: The event property of window is supported in IE and Google Chrome, but not in Firefox.

@John McCollum 2018-10-11 14:12:34

Thank you! The debugger didn't show an event under globals, which is what threw me.

Related Questions

Sponsored Content

3 Answered Questions

[SOLVED] Lexical Scope in JavaScript

2 Answered Questions

3 Answered Questions

1 Answered Questions

[SOLVED] assigning a clickHandler within the function and removing after

0 Answered Questions

1 Answered Questions

[SOLVED] Why doesn't a method reference keep track of this?

10 Answered Questions

[SOLVED] Simple JavaScript problem: onClick confirm not preventing default action

  • 2008-12-02 21:27:16
  • kafuchau
  • 179803 View
  • 36 Score
  • 10 Answer
  • Tags:   javascript html

2 Answered Questions

[SOLVED] Passing parameters to a event listener function in javascript

2 Answered Questions

[SOLVED] Where does this `#` in my array output come from?

3 Answered Questions

[SOLVED] Javascript Select-all checkbox suddenly not working

Sponsored Content