9

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.

Take my take as an example. I have a page which has a bunch of onclick events that now have to be handled by properties in the JS file

eg

var test = document.getElementById("i-am-element");
test.onclick = testEventListener;

My question is where exactly I should add this in the js file.

How I was planning to go about it was to have something like the following

$(document).ready(function() {
    var test = document.getElementById("test-me-shane");
    test.onclick = testEventListener;

    //add all the functions to different elements
});

myfunction1(){}
myfunction2(){}
myfunction3(){}

So that once the document is ready, only then are all the event listeners added. Is this acceptable or is there are more universally accepted way of doing it.

NOTE: I know this question may appear subjective so I'm going with the correct answer will be the most popular way you've seen seen event listeners added. I'm sure there must be a majority acceptance on this and I apologize in advance if its similiar to something like where you should declare variables, at the start or when you need them.

In Java, should variables be declared at the top of a function, or as they're needed?

Community
  • 1
  • 1
OVERTONE
  • 11,797
  • 20
  • 71
  • 87
  • Not sure if you will get the moon but study about event delegation. – Kumar Aug 03 '11 at 10:40
  • Well if the question cant be answered as to whether theres a right way to do it, perhaps someone could let me know if my way is wrong? – OVERTONE Aug 03 '11 at 10:47
  • I wrote a blog post on event delegation, this is my way to teach myself may be helpful to you, here it is http://www.kumarchetan.com/blog/2010/10/03/event-delegation-save-thou-webpage/, – Kumar Aug 03 '11 at 10:56

2 Answers2

11

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:

<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>

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);
    }
}
Ashwin
  • 562
  • 6
  • 14
Matt
  • 74,352
  • 26
  • 153
  • 180
  • Perhaps I should look into what a handler is before accepting this as the correct answer. Otherwise this is spot on. – OVERTONE Aug 03 '11 at 11:28
  • Ah never mind. I knew what handlers were. Just didn't know what they were called :3 – OVERTONE Aug 03 '11 at 11:30
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.

Giuseppe Di Federico
  • 3,501
  • 4
  • 20
  • 19
  • 10
    Thy shalt not bind events this way! – Kumar Aug 03 '11 at 10:41
  • 13
    "**Unobtrusive Javascript**"? – Matt Aug 03 '11 at 10:42
  • 2
    apparently It counts as embedded javascript and I'm only learning this today. Its a requirement that all events be handled as properties in the JS file and not in the HTML. Other than that, I have no problem with the onclick. – OVERTONE Aug 03 '11 at 10:45
  • Unobtrusive Javascript is definetly a pertinent reason – Giuseppe Di Federico Aug 03 '11 at 10:48
  • 1
    No don't follow what I said, it was just a clarification to your question, Matt is right +1, even if you solve your specific problem, you end up to mix html and js do it only if it's necessary, because it's a bad practise. – Giuseppe Di Federico Aug 03 '11 at 10:49
  • This will make your scope chain disgusting & frightening -- will inject creepy objects into it -- go read about it :) – treecoder Aug 03 '11 at 10:51
  • 4
    Funny how the era of AngularJS changed the way JavaScript developers react today to obtrusive code. They now easily consume `ng-click`s, `ng-submit`s, directives utilizing custom attributes to point to a function (`&`), stuff that mixes HTML with behavior (so difficult to maintain at times). It doesn't seem to be a problem anymore... But take a short example with `onclick` and - there you go - _thy shalt not bind events this way_! – user776686 May 17 '16 at 13:55