Onclick attribute vs eventListeners

I am rewriting the code of a website that I created several years ago, and I was wondering what is the most efficient way to handle the click event on an element?

I have a list of elements with links for editing them, and they are all written with an onclick="..."HTML attribute . Is this better, or should I use $.bind()or addEventListenerto process it? What is the best practice?

+5
source share
3 answers

It is considered best practice to use so-called unobtrusive javascript . This means that you separate the layout of your HTML from the behavior of the elements. Therefore, instead of using the onclick attribute, which mixes the structure of elements and behavior, you place your DOM structure in the markup, and then attach event handlers through javascript.

This means that it is considered best practice to use javascript for 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 code longevity and extensibility. This approach works very well with javascript libraries like jQuery.

From a performance point of view, you can achieve better performance through an unobtrusive approach to using JavaScript with an intelligent caching strategy.

javascript .

+1

addEventListener jQuery on\bind - , -HTML part-javascript.

.

, , .

+1

onclick, ", onclick?" - , .

If you are not using links to anything other than one event click, then onclickexcellent. However, if you want it to be bulletproof, you probably want to addEventListener. Actually, I have my own trio of addEvent/ fireEvent/ functions removeEventthat track events and handle browser inconsistencies for me (e.g. when using window.event), and this works very well.

+1
source

All Articles