What is the best way to add an event in JavaScript?

10,147

Solution 1

In my experience, there are two major points to this:

1) The most important thing is to be consistent. I don't think either of the two methods is necessarily easier to read, as long as you stick to it. I only get confused when both methods are used in a project (or even worse on the same page) because then I have to start searching for the calls and don't immediately know where to look.

2) The second kind, i.e. Event.observe() has advantages when the same or a very similar action is taken on multiple events because this becomes obvious when all those calls are in the same place. Also, as Konrad pointed out, in some cases this can be handled with a single call.

Solution 2

I think the first method is easier to read and maintain

I've found the opposite to be true. Bear in mind that sometimes more than one event handler will be bound to a given control.

Declaring all events in one central place helps to organize the actions taking place on the site. If you need to change something you don't have to search for all places making a call to a function, you simply have to change it in one place. When adding more elements that should have the same functionality you don't have to remember to add the handlers to them; instead, it's often enough to let them declare a class, or even not change them at all because they logically belong to a container element of which all child elements get wired to an action. From an actual code:

$$('#itemlist table th > a').invoke('observe', 'click', performSort);

This wired an event handler to all column headers in a table to make the table sortable. Imagine the effort to make all column headers sortable separately.

Solution 3

I believe the second method is generally preferred because it keeps information about action (i.e. the JavaScript) separate from the markup in the same way CSS separates presentation from markup.

I agree that this makes it a little more difficult to see what's happening in your page, but good tools like firebug will help you with this a lot. You'll also find much better IDE support available if you keep the mixing of HTML and Javascript to a minimum.

This approach really comes into its own as your project grows, and you find you want to attach the same javascript event to a bunch of different element types on many different pages. In that case, it becomes much easier to have a single pace which attaches events, rather than having to search many different HTML files to find where a particular function is called.

Solution 4

You can also use addEventListener (not in IE) / attachEvent (in IE).

Check out: http://www.quirksmode.org/js/events_advanced.html

These allow you to attach a function (or multiple functions) to an event on an existing DOM object. They also have the advantage of allowing un-attachment later.

In general, if you're using a serious amount of javascript, it can be useful to make your javascript readable, as opposed to your html. So you could say that onclick=X in the html is very clear, but this is both a lack of separation of the code -- another syntactic dependency between pieces -- and a case in which you have to read both the html and the javascript to understand the dynamic behavior of the page.

Share:
10,147

Related videos on Youtube

Mike
Author by

Mike

Updated on April 15, 2022

Comments

  • Mike
    Mike about 2 years

    I see 2 main ways to set events in JavaScript:

    1. Add an event directly inside the tag like this:

      <a href="" onclick="doFoo()">do foo</a>

    2. Set them by JavaScript like this:

      <a id="bar" href="">do bar</a>

    and add an event in a <script> section inside the <head> section or in an external JavaScript file, like that if you're using prototypeJS:

    Event.observe(window, 'load', function() {
        $('bar').observe('click', doBar);
    }
    

    I think the first method is easier to read and maintain (because the JavaScript action is directly bound to the link) but it's not so clean (because users can click on the link even if the page is not fully loaded, which may cause JavaScript errors in some cases).

    The second method is cleaner (actions are added when the page is fully loaded) but it's more difficult to know that an action is linked to the tag.

    Which method is the best?

    A killer answer will be fully appreciated!