Weird click event behavior in IE8 with prototypejs 1.7_rc2
I have some javascript click handlers that don't do what I want in IE8. What I want to do is call a handler on the first click and then call another handler on all subsequent clicks. The way I do that is put the original handler in the onclick attribute and then use that handler to erase the onclick attribute开发者_如何学Python and use Event#observe
to set up the handler that is called on subsequent clicks but for some reason IE8 refuses to cooperate. Instead of the following program flow
click->call originalHandler->erase originalHandler->set newHandler
I get the unexpected program flow
click->call originalHandler->erase originalHandler->set newHandler->call newHandler
I can't figure out why a single click event fires both handlers. Here's the snippet of the offending code, the pastie link and a link to a page that consistently reproduces the bug on my laptop with ie8.
//weird behavior in the latest prototype version with ie8
function originalHandler(event) {
Event.stop(event); //this doesn't help either, the event still triggers newHandler
var button = $('button');
alert("first click");
button.writeAttribute({onclick:null});
function newHandler(event) {
//this should only show up on the second click
//but it shows up on the first click as well
alert('second click');
}
button.observe('click',newHandler);
}
So to get the desired behavior I have to add an extra layer of indirection which seems really weird. So the following code fixes the issue with IE8 but breaks firefox and chrome behavior because now "second click" doesn't show up until the third click. Here's the pastie for the version that works on IE8 and the link to the page that behaves correctly on IE8 but requires an extra click on chrome and firefox.
function originalHandler(event) {
Event.stop(event);
var button = $('button');
alert("first click");
button.writeAttribute({onclick:null});
var newHandler = function(ev) {
button.stopObserving();
button.observe('click',function() {alert("second click");});
}
button.observe('click',newHandler);
}
Any ideas on how to fix this bug and get consistent behavior across all browsers?
I also asked on the prototype mailing list and the answer I got was that basically what's happening is that IE8 calls the DOM0 handler and then calls DOM2 handlers which is what I set up with Element#observe
and the way around it is to set up a delay so that the DOM2 handler is not set up until the first event bubbles all the way up without any DOM2 handlers in the way. Oh how I hate cross-browser compatibility.
精彩评论