DEV Community

Cover image for Don't use window.event
Ashutosh Biswas
Ashutosh Biswas

Posted on • Edited on • Originally published at ashutoshbw.github.io

2 1

Don't use window.event

Suppose you have the following HTML and JavaScript:

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

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

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);  
});
Enter fullscreen mode Exit fullscreen mode

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay