Javascript: Best Place to Register Event Handlers

This question is so basic, I'm sure it should be a duplicate of something, although I was looking for something similar .

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

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

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

But this goes against the overwhelming march towards the separation of logic and content in modern web development. Thus, in 2012, all logic / behavior should be executed in pure Javascript code. This is great and it leads to more convenient code. But you still need an initial hook that connects your HTML elements to your Javascript code.

Usually I just do something like:

<body onload = "registerAllEventHandlers()">

But ... that is still "tricking", is not it, because we are still using the built-in Javascript here. But what other options do we have? We cannot do this in the tag <script>in the section <head>, because at this moment we cannot access the DOM, since the page is not yet loaded:

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

Are we putting a tag <script>at the bottom of the page or something like that? How:

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

What is the best practice here?

+5
source share
4 answers

You can use window.onload:

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

Or if you use :

$(registerAllEventHandlers);

Usage onloadworks because it logs the event onloadimmediately, but fires it when the DOM is ready.

+2
source

, JavaScript . - .

, window.onload DOM ready. , , DOM .

0

, DOM . , IE 8 ( ) DOMContentLoaded ( gengkev , ).

registerAllEventHandlers body, , JavaScript HTML.

, window.onload, , (, CSS ..).

JavaScript, , DOM , IE. jQuery ready :

jQuery(document).ready(function () {
    // Your initialisation code here
});

:

jQuery(function() { … });

Prototype dom:loaded :

document.observe("dom:loaded", function() {
    // Your initialisation code here
});
0

Personally, I have no problem adding elements onlclick="doSomething();"to elements. No logic, just a function call.

All logic is where it should be: in a function defined in HEADor in a separate file.

Tell me what's the difference when you add href="somepage.html"or even href="somepage.html#someanchor"to tag A.

0
source

All Articles