Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Best place to register event handlers

This question is so basic, I'm certain in must be a duplicate of something, even though I've looked for something similar.

My question is basically: Where is the best place to initially register event handlers for HTML elements?

The easiest way to register an event handler is obviously to just do it inline:

<div id = "mybutton" onclick = "doSomething()">Click me</div>

But this goes against the overwhelming march towards separation of logic and content in modern web development. So, in 2012, all logic/behavior is supposed to be done in pure Javascript code. That's great, and it leads to more maintainable code. But you still need some initial hook that hooks up your HTML elements with your Javascript code.

Usually, I just do something like:

<body onload = "registerAllEventHandlers()">

But... that's still "cheating", isn't it - because we're still using inline Javascript here. But what other options do we have? We can't do it in a <script> tag in the <head> section, because at that point we can't access the DOM since the page hasn't loaded yet:

<head>
<script type = "text/javascript">
    var myButton = document.getElementById("mybutton"); // myButton is null!
</script>
</head>

Do we place a <script> tag at the bottom of the page or something? Like:

<html>
<body>
...
...
<script type = "text/javascript">
   registerAllEventHandlers();
</script>
</body>
</html>

What is the best practice here?

like image 349
Channel72 Avatar asked Nov 04 '22 23:11

Channel72


1 Answers

You can use window.onload:

<script type = "text/javascript">
  window.onload = registerAllEventHandlers;
</script>

Or if you use jquery:

$(registerAllEventHandlers);

Using onload works because it registers onload event immediately but fires it when DOM is ready.

like image 125
Tomasz Nurkiewicz Avatar answered Nov 09 '22 13:11

Tomasz Nurkiewicz