The Front End - Javascript Puzzler

Blog
The best minds from Teradata, our partners, and customers blog about whatever takes their fancy.
Teradata Employee

The following code works fine on most browsers but IE has a problem with it. Can you figure it out?

<head>
<title>Puzzler1</title>
</head>
<body onload="addClickHandler()">
<button id="myButton">Click Me</button>

<script>
function clickHandler(){
...
}

function addClickHandler(){
myButton = document.getElementById("myButton");
myButton.onclick = clickHandler;
}
</script>
</body>

Stay tuned to this blog for more puzzlers and pitfalls, useful tools, library evaluations, articles and tips related to javscript and front end development. Answer will be published soon.

2 Comments
Teradata Employee
in the function addClickHandler()
Declare the variable myButton in the following way : var myButton. It will work in IE too.

Try this :

Puzzler1



<SCRIPT><BR />function clickHandler(){<BR /> alert('hi');<BR />}<BR /><BR />function addClickHandler(){<BR /> var myButton = document.getElementById("myButton");<BR /> myButton.onclick = clickHandler;<BR />}<BR /></SCRIPT>

N/A
Without explaining why IE has a problem (I'll leave that for zizz), I'll just say that IE is trying to be clever. Their javascript handling has always had ways to try and make it "easier" for programmers, but in so doing has created inconsistencies with other browsers.