Skip navigation

The problem:

This simple page highlighted a problem on a web application using Prototype javascript library and a unassuming function name.

<html>

<head>
<script src=”prototype.js” ></script>
<script>
 function next(e) {
  alert(“window id is ” + window.id);
  alert(“a id is ” + $(myA).id);
  alert(this.id);
 }

</script>
</head>
<body id=”myBody” >

 <a id=”myA” href=”#” onClick=”next();return false;”>Click</a>
</body>

</html>

It was found that this page behaved as expected in IE (v7) but not in Firefox, Chrome or Safari. The onClick handler did not appear to be called.

Well the problem is due to a name clash we were completely unaware of. next is a function that prototype.js extends html element objects with. Our onClick handler turned out to be calling Element.next instead of our global javascript function.

To see this edit the onClick code,  replacing next() with alert(next).

The onClick handler uses the <a> element as its context and looks for a function in the local context before widening its search all the way up to the DOM global context (where our function is). In non-IE browsers it finds next is a method belonging to the Element object and executes it. In IE it does not find the next method until it finds our global function.

The solution:

Add an observer rather than an onClick function.

$('myA').observe('click', next);

Why? Prototype themselves explain why IE behaves differently.

Leave a comment

Design a site like this with WordPress.com
Get started