You really want all event listeners to be in one place; What for? Just for easy maintenance.
Because of this, it is best to place all event listeners in a place where you can guarantee that all the elements that you want to associate with event handlers are available.
This is why the most common place to bind event handlers occurs after the DOMReady event DOMReady $(document).ready() .
As always, there are some exceptions to the rule. Very sometimes, you may need to bind an event handler to an element as soon as available; which after closing the element tag has been defined. In this case, use the following snippet:
<div id="arbitrary-parent"> <h1 id="arbitrary-element">I need an event handler bound to me <strong>immediately!</strong></h1> <script>document.getElementById("arbitrary-element").onclick = function () { alert("clicked"); }</script> </div>
Another thing you should consider is how you are going to bind your handlers. If you stick with: DOMElement.onclick = function () { }; , you limit yourself to being bound to an event handler.
Instead, the following approach allows you to bind muliple handlers for each event:
function bind(el, evt, func) { if (el.addEventListener){ el.addEventListener(evt, func, false); } else if (el.attachEvent) { el.attachEvent('on' + evt, func); } }
source share