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.

 

Discussion
vijayakrishna 4 comments Joined 05/09
19 May 2009

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

Try this :

Puzzler1

Click Me

function clickHandler(){
alert('hi');
}

function addClickHandler(){
var myButton = document.getElementById("myButton");
myButton.onclick = clickHandler;
}

Maura 1 comment Joined 05/09
19 May 2009

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.

You must sign in to leave a comment.