Explain Codes LogoExplain Codes Logo

Why is using onClick() in HTML a bad practice?

html
event-delegation
unobtrusive-javascript
accessibility
Anton ShumikhinbyAnton Shumikhin·Mar 14, 2025
TLDR

Incorporating onClick() in HTML mixes structure with behavior, leading to messy code. Use addEventListener for a neat, modular practice:

// Instead of <button onClick="handleClick()">, do: document.querySelector('#myBtn').addEventListener('click', function() { alert('Button clicked! You win absolutely nothing! 🖱️'); }); // HTML: <button id="myBtn">Click me</button>

Key takeaways: addEventListener improves code legibility, maintainability, and aligns with contemporary best practices.

Inline onClick structure: Why it's not ideal

Cleanliness leads to clarity

The cardinal principle of separation of concerns advises keeping HTML, CSS, and JavaScript distinct. This boosts accessibility and code upkeep. An inline onClick() blurs these boundaries, resulting in entangled code where your logic and markup are inseparably intertwined.

Smooth operation across browser spectrum

Employing frameworks like jQuery, Vue.js, or Angular imparts universality for event handling across browsers, ironing out cross-browser compatibility issues. Inline handlers like onClick(), sadly, lack such benefits and can cause inconsistent behaviour.

Command center for event handling

By tying up all events in JavaScript, you can operate a central command for event management. Contrarily, inline onClick() handlers spread your JavaScript throughout the HTML, making global changes and adaptability for multiple scenarios a nightmare.

Better semantics, better accessibility

By focusing on semantic HTML, we use HTML tags for their intended purpose without picturing actions thereby improving accessibility. Inline onClick() attributes can result in a roadblock, veering away from this principle.

Event delegation might be your new best friend

Implementing event delegation allows you to attach a single listener to a parent element rather than each child—performance savior when handling multiple similar elements. Unfortunately, inline onClick() offers no such optimization.

Ensuring principle of graceful degradation

The idea of graceful degradation ensures even when JavaScript fails or is disabled, your site remains functional. Inline onClick() attributes can lead to a bottleneck hindering this principle.

Easy plugins, more reusability

Centralizing JavaScript event bindings leverages reuse and modularity. Use classes and data attributes to store info and make the script agnostic of specific HTML markup—unlike inline onClick(), which is stubbornly element-specific.

Control of popups

Avoid inline onClick="window.open()" for popups. Instead, use the window.popup() function within an event listener centralizing control of these actions within JavaScript.

Scoping with encapsulation

Immediate Invoked Function Expressions (IIFEs) ensure variables and functions stay encapsulated, preventing pollution of the global scope. Inline onClick() handlers can unintentionally expose functions and variables to the global scope.

Start simple, then go fancy

Start with basic, functional HTML, then progressively enhance it with unobtrusive JavaScript. This ensures the site remains functional at the core level, while the JavaScript layer adds enhanced interactivity.

Fast track to organized, accessible code

Unified approach with addEventListener

Use addEventListener for handling events, permitting multiple event functions without conflict and fostering code encapsulation.

// Instead of the awkward 'onclick', we do: elem.addEventListener('click', function() { console.log("You've got a friend in Me...thods! 😄"); });

Keeping scope clean with modules

Incorporate event listeners within modules or IIFEs for scoped interaction that keeps the global scope clean. This ensures the code manages only the required parts, enhancing clarity and improving maintenance.

Keeping up with modern practices

Using modern JavaScript Frameworks like React, Vue or Angular can be beneficial for a robust event handling. They provide modularity, scalability, and maintainable solutions which are required for large codebases.