Front-End Quiz Part 3, Adding Events to Elements


What's the best way to add JavaScript "onclick" event behavior to a link?

  1. Add an onclick="" attribute to the <a> tag.

    My opinion: this is a nasty, outdated way of doing things that needs to be euthanized ASAP. It's the most prevalent method as of 2007, but mixing scripting commands with HTML is just as bad as mixing presentational commands with HTML, and for the same reasons. Presentation should be removed from content via external CSS files, and behavior should be removed from content via external JavaScript files. Even if it seems justifiable to throw in a quick onclick="" attribute for convenience's sake, it risks getting accidentally overwritten by more sophisticated event attachment methods that deploy via external scripts.

  2. In a script, use document.getElementById("someId").onclick = function() { ... }

    Better, but still nasty, IMO. This method is a vast improvement over inline event handler attributes such as <a onclick="">, but it still only lets you assign one event handler per element, and succumbs to the common problem of events being accidently overwritten, since there is only a single onclick property per element.

  3. Use event attachment, preferably via some kind of event library that abstracts away browser differences.

    My personal favorite. Event attachment lets you assign an arbitrary number of events to the same element. This is especially useful for the window "onload" event, which often needs to spawn multiple actions.


Comments:

Post a Comment:
Comments are closed for this entry.
About

My name is Greg Reimer and I'm a web technologist for the Sun.COM web design team.

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today