Creating functions conditionally with Internet Explorer In WebTech, 754 days ago 

Here is another strange Internet Explorer (yes, 6 and 7 flavour) behaviour.

The problem: your library should define a function if and only if it is not yet defined. The case is for the famous $ Prototype function, that is also defined (sigh) by Drupal in its all-purpose drupal.js

In JavaScript you can legally write something like this:

if (typeof $ == 'undefined') {
  function $(id) {
    return document.getElementById(id);
  }
}

Firefox will define the function only if it is not yet defined (the Prototype version is slightly more complex and must be left untouched).

But IE will not. It defines ANYWAY the $ function, thus overwriting the pre-defined Prototype one (that is BAD).

The workaround is quite simple. The function have to be defined as an object, not via the “usual way”.

That is:

if (typeof $ == 'undefined') {
  var $=new Function("id", "return document.getElementById(id);");
}

Comments

  1. ZER0 said:

    if (typeof $ == “undefined”)
    window.$ = function(id) {
    return document.getElementById(id);
    }

    Posted on 11/10/06 11:39 AM    #

  2. Claudio said:

    Yeah, right. Just another method. Thank you.

    Posted on 11/10/06 01:05 PM    #

commenting closed for this article

This site

Browse by category

Contacts

Feed from feedburner Subscribe to this feed with Bloglines

Creative Commons

XFN Friendly