Monday, April 04, 2005

JavaScript and Anchors

I've been doing a lot of reading on JavaScript relating to various scripts on which I've been working. One thing that's come up that's interesting, annoying, and problematic all at once relates to HTML element IDs and page anchors (named anchors).

Interesting
According to the the W3C spec an element ID should also act as a page anchor. (Note: this is based on a small amount of reasearch so my interpretation may be flawed.) This is a very nice feature of the spec that fits in well with my show/hide script. Based on limited testing it appears that modern browsers support this.

Annoying
Older browser do not support this feature. This means that for legacy browsers (such as Netscape Navigator 4.x) I also have to provide the named anchor. This isn't really a problem, but it would've been nice to be able to just use the element ID.

Problematic
While IE may support this feature it does something related that's a bit annoying. It provides the reverse functionality: every named anchor on a page also receives a matching ID. I'm not sure if this is something that's addressed in the spec. This feature is annoying because it interferes with the scheme I was using for the show/hide JS.

I was hoping to modify the show/hide JS so that implementation would be less involved. Esentially the changes I've made would require only that the show/hide content be contained within a DIV that has a class of "shContent". (Note: I have yet to hammer out how to handle show/hide image cues.) The IE effect requires a little more care during implementation because the backup anchor tag has to be within the DIV or else the wrong element will be on the receiving end of the show/hide and the script will not work correctly.

In addition to this minor annoyance, I'm not sure how this affects IEs DOM. IE (and other browsers for that matter) appear to function just fine even with duplicate IDs in a document, but it seems like that's something that should cause an exception. This is likely something that could cause problems down the road.


Update 2005-04-27:
I just glanced through the W3C spec and it appears that IE interprets things correctly, ::gasp:: who knew!

Basically, the ID attribute and the name attribute (when applied to an anchor tag) inhabit the same name space. Since the ID attribute must be unique, you can't have a named anchor that matches another element's ID. Additionally, anchors must not match when a case-insensitive comparison is made (another thing I hadn't ever considered).

Though things are functional at present it looks like I'll need to work on making my code a little more kosher with respect to the spec.