When working with JavaScript, you’ll often need to respond to user actions like clicks, keyboard input, and more. There are a few common ways to handle events in JavaScript, but not all methods are created equal.
Let’s take a look at three ways to handle DOM events, and why one of them stands out as the best practice.
1. Inline Event Handlers (Avoid)
The first approach is using inline event handlers directly in HTML. This might look like this:
<button onclick="alert('Clicked!')">Click Me</button>
While this is quick and easy, it comes with several downsides. It mixes HTML and JavaScript, making your code harder to maintain and debug. It also doesn’t offer flexibility if you want to add multiple events or complex logic.
2. DOM Property (Better)
A better method is to use the DOM property of the element directly in JavaScript. Here’s an example:
let button = document.querySelector("button");
//or you can also use this way
//<button type="button" class="btn btn-secondary mt-4" id="secbtn" onclick="secbtnfn()" > Secondary </button>
button.onclick = () => console.log("Clicked!");
This approach keeps JavaScript separate from HTML, which is a step forward in terms of maintainability. However, it has a limitation—you can only assign one event handler per element. If you try to assign another event handler, it will override the previous one. For example:
let button = document.querySelector("button");
button.onclick = () => console.log("First event");
button.onclick = () => console.log("Second event"); // Overwrites the first
3. addEventListener (Best Practice)
The most flexible and professional way to handle events is by using the addEventListener method. This allows you to attach multiple event listeners to the same element, without worrying about overwriting them. Here’s the syntax:
document.getElementById("sucbtn").addEventListener("click", () => {
console.log("Success button clicked");
});
document.getElementById("sucbtn").addEventListener("click", () => {
alert("Multiple events on button click! Check the console as well.");
});
Why is this the best approach?
- Multiple Events: You can attach several listeners to the same element, as shown in the example.
- Event Options: It gives you more control with features like event capturing, bubbling, and passive events.
- Cleaner Code: By separating HTML and JavaScript, your code is easier to maintain and debug.
Conclusion: Use addEventListener
As a professional developer, always use addEventListener for handling DOM events. It’s the most flexible and clean way to manage events in your JavaScript code. By keeping things modular and separate, you’ll build maintainable, scalable web applications. Avoid inline handlers and DOM properties when you can!
