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");
</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?
source
share