Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 275
Aleks G Avatar asked Apr 25 '26 03:04

Aleks G


1 Answers

You should separate structure (HTML), style (CSS) and behavior (JS).

Events are behaviors of the page - do it in JS.

Don't place them anywhere else, not in the HTML, not in the CSS (if ever it were possible).

like image 165
Joseph Avatar answered Apr 26 '26 18:04

Joseph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!