Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onclick attribute vs eventListeners

I'm re-writing the code of a website I created a few years ago, and I was wondering what was the most efficient way to handle the click event on an element?

I have a list of items with links to edit them, and they're all written with the onclick="..." HTML attribute. Is it better that way or I should use $.bind() or addEventListener to handle it? What's the best practice?

like image 426
Samuel Bolduc Avatar asked Oct 05 '22 05:10

Samuel Bolduc


3 Answers

It is considered best practice to utilize what is called unobtrusive javascript. What this means is you separate the layout of your HTML from the behavior of the elements. So instead of using the onclick attribute, which mixes up element structure and behaviour, you layout your DOM structure in markup and then attached event handlers via javascript.

What this means is that is considered best practice to use javascript to attached event handlers, as follows:

<html>
   <script>
        ... bind event handlers to your DOM and set behaviours here
   </script>
   <body>
       .... layout your DOM here
    </body>
<html>

This has advantages for long-term code maintainability and extensibility. This approach works very nicely with javascript libraries such as jQuery.

In terms of performance, you may be able to achieve performance gains via an unobtrusive javascript approach by using an intelligent caching strategy.

For more information on unobtrusive javascript, see here

like image 185
Joe Alfano Avatar answered Oct 17 '22 14:10

Joe Alfano


addEventListener or it's jQuery version on \ bind is the best practice as it separates the visual part-HTML from the functional part- javascript.

Separates of concerns.

If the code is written already, I wouldn't change it, it's not that important.

like image 42
gdoron is supporting Monica Avatar answered Oct 17 '22 15:10

gdoron is supporting Monica


Many people will discourage the use of onclick because "what if you want to add another onclick event?" - personally I have never had this issue, but I can sort of understand.

If you're not using the links for anything other than a single click event, then onclick is perfectly fine. However, if you want it to be bulletproof, you probably want addEventListener. I actually have my own addEvent/fireEvent/removeEvent trio of functions that keep track of events and handle browser inconsistencies for me (bringing in window.event, for instance) and this works quite well.

like image 1
Niet the Dark Absol Avatar answered Oct 17 '22 13:10

Niet the Dark Absol