Search code examples
javascriptjqueryhtmlevent-delegation

Html onclick attribute vs script's onclick event listener


As a beginner I was just experimenting with various HTML elements and scripts. I then came across the HTML attribute onclick.

As I had done more of scripting before my experiments with HTML, I was wondering if there is any difference between calling the function via the DOM itself or through JS/Jquery's event listener.

E.g:-

html

<button onclick="myFunc()" id="btn1">button 1</button>

VS Script

<button id="btn2">button 2</button>

<script>
    $(document).on('click','#btn2",function(){
        //code here
    });
</script>

I would also like to know the pros and cons and which of the two is best practice.

Please do let me know if I am breaking the rules of asking questions here so I could modify/delete the question.


Solution

  • I would also like to know the pros and cons and which of the two is best practice.

    Pros of "VS Script":

    • elements can be added without having to add click handlers, even after function has been declared
    • A single callback function can handle clicks (or other events) on various elements and then delegate the action to various functions...
    • Using an onClick or similar attribute is a mix of JS within the HTML - this goes against the Separation of Concerns principle. With the "VS Script" the logic is separate from the markup.
    • can avoid memory-leaks
    • lends itself better to event delegation
    • Code sanitizers may complain about inline scripts in attributes like onclick, onmouseout, etc.

    Cons of "VS Script":

    • Elements added to the DOM after the click handler has been registered won't trigger the click handler (see this answer for more details).
    • Support from older browsers may make achieving this more complex (e.g. addEventListener before IE 9... though if you are using a library like jQuery (like you mentioned), then this is likely handled for you...
    • More work may need to be done to get attributes of the element for which the event occurred on

    For a more detailed explanation, see this answer.