Christian Heilmann

\”More content\” links, cloneNode(), YUI and Safari/MSIE issues

Monday, August 14th, 2006 at 10:23 pm

cloned sheep When I was creating a proof of concept the other day about how to create ‘more content’ links with JavaScript and the YUI I stumbled across an interesting problem with the YUI Event utility.

The Event Utility is IMHO the cat’s pajamas as it solves a lot of issues the tried and true addEvent didn’t: It retains the scope allowing you to use “this” in the listener method, makes preventDefault work in Safari and also allows you to send another custom object to the listener method, all of which make is a lot easier to write unobtrusive JavaScript without the memory leaks.

Now, the interesting problem I stumbled upon is that if you do the following

  • create a new link
  • add attributes, content and all that jazz
  • apply an event handler
  • clone the link
  • apply another handler to the second link

you’re in for trouble. Safari applies both handlers to the first link and none to the second, and MSIE applies both the first and the second handler (in reverse order) to the second link! Here’s the test case using YUI. The MSIE problem of the double handler on the second link also happens when you use the tradional addEvent.

I talked to the YUI folks and Adam told me that applying unique IDs to the links solves the issue in Safari, however it doesn’t make a difference in MSIE.

The lesson to take away:

If you clone elements, make sure to clone them before you apply the handlers, and remove all handlers just to be on the safe side

A shame, as I really like the idea of cloning elements. The other option of course is a constructor method for repeated elements.

Share on Mastodon (needs instance)

Share on Twitter

My other work: