Skip to content Skip to sidebar Skip to footer

Best Practice On Adding Event Listeners (javascript, Html)

I know I may be asking for the moon here but I'm looking for some experienced opinons on the best way to add event listeners or rather 'When' or 'Where' to add them in the js file.

Solution 1:

You really want to be able to add all your event listeners in the same place; why? Simply for ease-of-maintenance.

Because of this, the best place to put all your event listeners is in a place where you can guarantee all elements you'll possibly want to bind event handlers to are available.

This is why the most common place to bind your event handlers is after the DOMReady event has fired $(document).ready().

As always, there are some exceptions to the rule. Very occasionally, you might want to bind an event handler to an element as soon as it is available; which is after the closing tag of the element has been defined. In this instance, the following snippet should be used:

<divid="arbitrary-parent"><h1id="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>

The other thing you should consider is how you are going to bind your handlers. If you stick to: DOMElement.onclick = function () { };, you're limiting yourself to binding on handler per event.

Instead, the following approach allows you to bind multiple handlers per event:

function bind(el, evt, func) {
    if (el.addEventListener){
        el.addEventListener(evt, func, false);
    } else if (el.attachEvent) {
        el.attachEvent('on' + evt, func);
    }
}

Solution 2:

Is there a specific reason why you don't simply specify the association when you declare the element in the html <someTag id="i-am-an-element" onclick="functionToTheEventToExecute()"> </someTag> I guess so.

Post a Comment for "Best Practice On Adding Event Listeners (javascript, Html)"