"bug" with onclick handlers in IE
Wednesday, June 25th, 2008I had an issue today with Internet Explorer. An object with an onClick handler worked fine in Firefox and Safari, but in IE the handler only fired every other click. In the course of debugging I discovered that if I clicked slowly, it worked on every click. I realized that this was because IE must be registering an onDblClick event instead of two onClick events. A little testing confirmed this. I searched to see if someone else had the same problem, and found this page. User jamescover had the same issue and found a solution: use the onMouseUp event to handle clicks instead of onClick. He also directed the focus in the onMouseDown event, but I found that part to be unnecessary in my application. A demo of his solution can be found here. I’ll reproduce the code in this post in case that page ever gets taken down:
<script type=”text/javascript”>
<!–
var x = 0;
function addX(){
document['oFrm']['num'].value = x;
x++;
}
var y = 0;
function addY(){
document['oFrm2']['num2'].value = y;
y++;
}
//–>
</script>
This one invokes the function <b>onclick</b>
<form name=”oFrm”>
<input type=”text” name=”num” size=”5″ />
<input type=”button” value=”add” onclick=”addX();” />
</form>
This one focuses the text field <b>onmousedown</b>, then invokes the function <b>onmouseup</b>
<form name=”oFrm2″>
<input type=”text” name=”num2″ size=”5″ />
<input type=”button” value=”add” onmousedown=”this.focus();” onmouseup=”addY();” />
</form>