DEV Community

Cover image for Why I don’t use JS event handlers
Jaden Concord
Jaden Concord

Posted on

Why I don’t use JS event handlers

JavaScript gives you the ability to attach events to the dom without any mention of the action in the HTML. This is an incredibly useful way to attach events cleaning up you HTML, putting the JS where it belongs. Some frameworks take care of this but this is for those that don’t use one but do you even need a front end framework? Most tutorials and courses tell you that you should use JS event handlers instead of putting events in the HTML. Although this is effective in simple sites, it is not always the best in JS rendered applications. Why? Because if you were generating sidebar items for example, you would have to make each element have a different query. Then you would have to select each item and attach a custom event to each item. That’s not a very good approach.

Let me further illustrate this, If you have the array:

[home, dashboard, editor]
Enter fullscreen mode Exit fullscreen mode

You will want to generate three tags like this:

<li onclick="openPage('home')">home</li>
<li onclick="openPage('dashboard')">dashboard</li>
<li onclick="openPage('editor')">editor</li>
Enter fullscreen mode Exit fullscreen mode

You don't want to create three items with different id's or classes and loop through them to add events to them in JS.

Your probably thinking of course you would do it this way however when I was first leaning JS I did not know this. So should you use html events only when you have to and use JS events most of the time? I would say it depends on the application or site you are developing also on personal preference. I like putting my events in my HTML files because it makes it easier to integrate different pages and integrations. I am not saying that you should put the code in the onclick attribute or whatever event no, but you should only put a function in it with parameters that identify it for the script. I like putting the events in the HTML but I still use JS events like for document for some things. I also have created some pages where xml pages are loaded and having events in the content is the only way to make it a flexible application (for that app).

What are your thoughts?

Top comments (0)