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?
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With