DEV Community

Cover image for πŸ›‘ Why You Should Avoid the onclick Attribute in Your Code
Max Programming
Max Programming

Posted on • Originally published at blog.usmans.me

πŸ›‘ Why You Should Avoid the onclick Attribute in Your Code

Hey everyone! It's been a while since I wrote my last article. But here I am with another topic that might be informational to you πŸ™‚.

This time I am writing about why you should avoid the onclick attribute in your HTML and JavaScript code.

meme - you avoiding onclick

This article is not particularly about click events but rather all events in HTML and JS. The click event is a good and easy example to explain.

First, I will try to explain the various ways to handle click events or rather any events in JavaScript.

Different Ways to Handle Click Events

There are three ways I know to handle click events in HTML and JavaScript (comment below if you know more).

1. Using the onclick attribute

The first way I learned was by using the onclick attribute in HTML and calling a function that was written in JavaScript.

It is maybe the easiest way to handle click events. As there is nothing complicated. Everything makes sense.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>The onclick way</title>
  </head>
  <body>
    <button onclick="whenButtonClicked()">Click me</button>
    <script>
      function whenButtonClicked() {
        alert('button clicked');
      }
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

In the code above, we create a function inside our JavaScript that we then call when the button is clicked.

It will result in something like this πŸ‘‡

button is clicked and an alert is shown

2. Using the addEventListener function

The second way I learned was by using the addEventListener function inside JavaScript. I saw it for the first time in this tutorial.

At first, I felt this was unnecessary as the onclick felt easier. But with time and building large projects, I understood why this makes more sense.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>The onclick way</title>
  </head>
  <body>
    <button id="btn">Click me</button>
    <script>
      const btn = document.getElementById('btn');

      function whenButtonClicked() {
        alert('button clicked');
      }

      // 1. either pass the function
      btn.addEventListener('click', whenButtonClicked);
      // 2. or use anonymous function
      btn.addEventListener('click', () => {
        alert('button clicked');
      });
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

What happens here is you first select the button inside your JavaScript code with id or class etc. And then register/add an event listener called click. Then either pass the function in or use an anonymous function.

This is better because when you are going to build something large the first way, your JavaScript code will get mixed with HTML. Then maintaining your code will be very hard.

You can also remove an event listener using the removeEventListener method. By just passing in the function that was used previously.

function whenButtonClicked() {
  alert('button clicked');
}

// add event listener
btn.addEventListener('click', whenButtonClicked);
// remove event listener
btn.removeEventListener('click', whenButtonClicked);
Enter fullscreen mode Exit fullscreen mode

3. Using the onclick property

This is by far my favourite way to handle events.

  • It's as straightforward as the first one.

  • Separated from HTML as the second one.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>The onclick way</title>
  </head>
  <body>
    <button id="btn">Click me</button>
    <script>
      const btn = document.getElementById('btn');

      function whenButtonClicked() {
        alert('button clicked');
      }

      // 1. either pass the function
      btn.onclick = whenButtonClicked;
      // 2. or use anonymous function
      btn.onclick = () => {
        alert('button clicked');
      };
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

What we do in this piece of code is that we assign the onclick attribute to a function (same as the second way).

The downside of using this method is that you cannot assign multiple event listeners. If you use addEventListener. With that, you can add multiple functions to one element. And not to mention you also cannot use something like removeEventListener

So What's Wrong with onclick?

Now let's come to the main section of the article.

The onclick attribute is not recommended in HTML because it is considered to be a bad practice to use inline JavaScript in your HTML code.

Instead, it is better to separate your JavaScript code from your HTML code and use event listeners to handle events in your web page. This makes your code easier to read, maintain, and reuse.

In general, it is better to avoid using the onclick attribute in HTML and to use event listeners instead, as this allows you to keep your JavaScript code separate from your HTML code and makes it easier to manage and maintain.

Additionally, using inline JavaScript in your HTML can make your code more difficult to maintain and update. If you need to change the behaviour of your web page, you will have to go through your HTML code and update all of the onclick attributes, which can be time-consuming and error-prone.

Conclusion

I hope this article helped you out and made you better!

I would love to hear your thoughts on this topic. Please share your ideas and experiences in the comments section below.

Top comments (4)

Collapse
 
styren profile image
Buster Styren

Okay so it's bad practice, but why? And in what way does event listeners make the code easier to manage and maintain?

The only reason stated is that you need to update in several places when the implementation changes but that wouldn't be the case in your example since the implementation is defined in the script tag.

Collapse
 
maxprogramming profile image
Max Programming • Edited

I actually chose this very example so that people who know only about onclick can also easily understand.

When it comes to managing and maintaining code, it makes sense to me using addEventListener or the onclick method because that way, the code stays inside of JavaScript. I don't have to go back-and-forth and also, the intellisense from the IDE works better that way. Separation of code is important.

I came up with this idea because I saw one of my friends using oninput and they caused a lot of bugs that made me confuse too. Even in a relatively simple application πŸ™‚

Also in Kotlin, it is recommended to use the event listeners inside the Activity Code rather than the XML and calling the function right there.

Collapse
 
ddanielsantos profile image
Daniel Santos

idk if allowing the code to be anywhere is a good idea, with onclick you have only one place to check if something is going wrong, with event listeners you have extra steps and uneccessary complexity

Collapse
 
maxprogramming profile image
Max Programming

While using event listeners, the code remains inside JavaScript.

If you build a fairly simple project which includes tens of buttons with same functionality but different values, like a calculator, it would make sense to use onclick instead. Because in that case using event listeners will result in much larger code.

But when building a normal application with having different buttons do different things, it is better to keep all the logical code inside JavaScript.