Don’t use window.event

Suppose you have the following HTML and JavaScript:

<button id=”btn”>Click me</button>

let myBtn = document.querySelector(“#btn”);

myBtn.addEventListener(“click”, () => {
console.log(event);
});

What do you think c…


This content originally appeared on DEV Community and was authored by Ashutosh Biswas

Suppose you have the following HTML and JavaScript:

<button id="btn">Click me</button>
let myBtn = document.querySelector("#btn");

myBtn.addEventListener("click", () => {
  console.log(event);  
});

What do you think clicking on the button will happen?

If you think it will not work, saying event is not defined or something like this, you will surprisedly get the right Event object for that event, unless your browser has stopped caring about it.

What actually happens is that event is a read-only property of window and outside of event handlers, this event is always undefined. But when an event happens, only inside that corresponding event handler, it has respective Event object as it's value if your browser has support for it.

⚠️ Warning: It's not recommended by MDN and is a deprecated feature and it may be dropped if supported. So you should avoid accessing Event objects like this and instead use the first parameter of event handler for accessing it. For example:

myBtn.addEventListener("click", event => {
  console.log(event);  
});


This content originally appeared on DEV Community and was authored by Ashutosh Biswas


Print Share Comment Cite Upload Translate Updates
APA

Ashutosh Biswas | Sciencx (2022-04-17T01:20:18+00:00) Don’t use window.event. Retrieved from https://www.scien.cx/2022/04/17/dont-use-window-event/

MLA
" » Don’t use window.event." Ashutosh Biswas | Sciencx - Sunday April 17, 2022, https://www.scien.cx/2022/04/17/dont-use-window-event/
HARVARD
Ashutosh Biswas | Sciencx Sunday April 17, 2022 » Don’t use window.event., viewed ,<https://www.scien.cx/2022/04/17/dont-use-window-event/>
VANCOUVER
Ashutosh Biswas | Sciencx - » Don’t use window.event. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/04/17/dont-use-window-event/
CHICAGO
" » Don’t use window.event." Ashutosh Biswas | Sciencx - Accessed . https://www.scien.cx/2022/04/17/dont-use-window-event/
IEEE
" » Don’t use window.event." Ashutosh Biswas | Sciencx [Online]. Available: https://www.scien.cx/2022/04/17/dont-use-window-event/. [Accessed: ]
rf:citation
» Don’t use window.event | Ashutosh Biswas | Sciencx | https://www.scien.cx/2022/04/17/dont-use-window-event/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.