Search code examples
javascripthtmlevents

Static vs. dynamic event attachments on HTML elements


As the title may be slightly ambiguous or not clear, I'll first explain what I mean by the two methods. In my HTML/JS code, I mix two ways of attaching events to my html elements: (1) what I call "static":

<input name="abc" class="def" id="xyz" onclick="do_something"/>

and (2) what I call "dynamic":

<input name="abc" class="def" id="xyz" />

with

$(document).ready(function() {
    $('#xyz').click(function() { do_something; })
});

Note that this is not a real code, just something to present as an example. I don't have to use jquery either, the same could be achieve with simple

document.onload = function() {
    document.getElementById('xyz').onclick = function() { do_something; }
}

Usually if the logic is quite simple (e.g. enable/disable on element on click of another), I would use static method. If the logic is more complicated, I would use dynamic one. Of course, I can also use static method with onclick="function_call()" - and put all the complicated logic into this function, although this is something I may have left in the code from legacy days (from years ago).

Now, I have met people that would swear by one of the methods and deride anybody that would use the other, claiming that the other method is wrong/difficult-to-read/slower/add-your-own-explanation. HoweverI have not found any really good reason to always stick with one method and keep mixing these up. Am I missing something or is there really no good reason to stick with one method?


Solution

  • My practice is to follow the rule of least surprise.

    If my page is 99% HTML and just 1 or 2 lines of Javascript then I use inline events <div onclick=""> to minimize the amount of fluff in the page due to addEventListener baggage.

    If my page is too complex with too many elements and if separation of behavior will cause large chunks of getElementById or $('.tree') sections, which actually inhibits resadability (therefore increases surprise level) then I also use inline event. How and why

    Otherwise I use the expected separation of structure and behavior rule.