You will be using the onClick() attribute in HTML while developing the web pages. It looks simple to add the onClick=”myFunction()” to an element, and it may also work. But using this attribute directly on the HTML is not a good practice. In this blog, we will discuss some alternative ways to use these attributes.
Table of Contents:
What is onClick() in HTML?
You can handle the click event directly in HTML using the onClick() attribute. When you click on the element, it runs the JavaScript code.
Example:
<button onClick="alert('Button clicked!')">Click Me</button>
It works by triggering the alert box after clicking the button. But it has some disadvantages, such as messy code, maintenance, and flexibility issues.
Alternatives to add onclick() in HTML
You can use some alternative methods to fix the issues like messy code, maintenance, and flexibility issues.
Learn Web Development and Launch Your Career
Professional Web Development Courses For Beginners
Separation of Concerns (HTML, CSS, and JavaScript Should Be Separate)
You can keep the HTML, CSS, and JavaScript separate; this is one of the key principles for the modern approach to web development. When you use the onClick() event in your HTML code, it gets mixed with the JavaScript, which may cause some of the issues discussed above.
Example:
<button onClick="changeText()">Click Me</button>
<script>
function changeText() {
document.querySelector('button').textContent = 'Clicked!';
}
</script>
You can use JavaScript separately for a better approach:
Example:
<button id="myButton">Click Me</button>
<script>
document.getElementById('myButton').addEventListener('click', function() {
this.textContent = 'Clicked!';
});
</script>
Harder to Debug and Maintain
You may find it confusing if the onclick() event is written all over the code.
Imagine your website has many elements with onClick() written inline. If something goes wrong, debugging becomes a huge hassle since you’d have to search through all the HTML to find the problem.
Security Risks (Inline JavaScript is Vulnerable to XSS Attacks)
Using onClick() in HTML can make your website easier to hack through Cross-Site Scripting (XSS) attacks. Hackers can insert harmful JavaScript into your site, which is why it’s better to handle events securely in separate JavaScript files.
For example, if your site allows users to submit comments, an attacker could inject this:
<button onClick="alert('Hacked!')">Click Me</button>
If an admin clicks this button by mistake, hackers could steal sensitive data. To stay safe, use addEventListener() in JavaScript instead. It makes it harder for attackers to insert harmful scripts into your site.
Difficult to Reuse Code
If you have lots of buttons doing the same thing, using onClick() inline means you’ll have to repeat the same JavaScript code over and over. This goes against the DRY (Don’t Repeat Yourself) rule in programming, which helps keep your code clean and efficient. Instead, use a single JavaScript function to handle them all.
Example of Bad Practice
<button onClick="changeColor()">Button 1</button>
<button onClick="changeColor()">Button 2</button>
<script>
function changeColor() {
document.body.style.backgroundColor = 'blue';
}
</script>
Output:
Better Approach:
You can see in this code that we don’t add an onClick() function to every button. JavaScript adds an event listener to all the buttons.
<button class="colorButton">Button 1</button>
<button class="colorButton">Button 2</button>
<script>
document.querySelectorAll('.colorButton').forEach(button => {
button.addEventListener('click', () => {
document.body.style.backgroundColor = 'blue';
});
});
</script>
Usually, the HTML document is read by the browser from top to bottom. If they find an onClick() event in your code, they should save it in memory and run it afterward. The page can slow down if you have many inline handlers.
To avoid this issue, you can go for the addEventListener() in JavaScript for better browser management, and it can also help in loading the page smoothly.
Harder to Apply Global Event Handling
You will be handling multiple events in some cases. The onClick() in HTML makes the process difficult. Example: The onclick() handler won’t be working if you add the new button until you add it manually.
Example of a Bad Approach
<div id="buttonContainer">
<button onClick="alert('Clicked!')">Click Me</button>
</div>
<button onClick="addButton()">Add New Button</button>
<script>
function addButton() {
let newButton = document.createElement('button');
newButton.textContent = 'New Button';
newButton.setAttribute('onClick', "alert('Clicked!')");
document.getElementById('buttonContainer').appendChild(newButton);
}
</script>
Output:
Best Approach:
This code makes the new and existing button works automatically without any extra event handlers.
<div id="buttonContainer">
<button class="dynamicButton">Click Me</button>
</div>
<button id="addNewButton">Add New Button</button>
<script>
document.getElementById('buttonContainer').addEventListener('click', function(event) {
if (event.target.classList.contains('dynamicButton')) {
alert('Clicked!');
}
});
document.getElementById('addNewButton').addEventListener('click', function() {
let newButton = document.createElement('button');
newButton.textContent = 'New Button';
newButton.classList.add('dynamicButton');
document.getElementById('buttonContainer').appendChild(newButton);
});
</script>
Get 100% Hike!
Master Most in Demand Skills Now!
Conclusion
You can avoid using onClick() in HTML because it may lead to messy and slow code. You can use addEventListener() in JavaScript as an alternative for this purpose, and it can also give you better performance of the page. By doing this, you can also prevent the page from XSS attacks, and it can also be reusable. Following these best practices will help you to develop better web pages.
Why is using onClick() in HTML a bad practice? – FAQs
Q1. Why is mixing JavaScript with HTML a problem?
It reduces the readability and maintainability of the code. It may be difficult to debug and update the code further.
Q2. What are the performance implications of using onClick() in HTML?
It reduces the performance of the webpage, especially for large applications. It led to the creation of global functions and leakage of memory.
Q3. How does it affect accessibility?
Using onClick() directly in HTML can make it harder to ensure accessibility compliance.
Q4. What are the alternatives to onClick() in HTML?
You can use JavaScript’s addEventListener() method as an alternative to onClick().
Q5. Is it ever okay to use onClick() in HTML?
You can use onClick() for simple and small projects. You can follow the best practices for large and complex projects.