Attached event triggering if event is same as current event

Posted by Psytronic on Stack Overflow See other posts from Stack Overflow or by Psytronic
Published on 2010-05-26T20:24:55Z Indexed on 2010/05/26 21:11 UTC
Read the original article Hit count: 545

I have a button which start/stops a timer. When I click it, I remove the current event handler, and attach the opposite one. Ie, click "Stop", and the "Start" function is attached for the next click.

However in IE (7), not sure about 8. The newly attached event is also triggering after the original function is finished:

Lifeline in IE7:
Button pushed --> "Stop" function begins --> "Stop" function removed --> "Start" function attached --> "Stop" function finishes --> "Start" function is called.

I know it's to do with the attaching event bit, because If I remove it, the Start event doesn't fire.

This seems a bit odd, as I have the same situation in the "Start" function, ie, "Start" removed, "Stop" called. But this doesn't seem to cause an infinite loop, thankfully.

if(btn.attachEvent){
  btn.detachEvent("onclick", stop);
  btn.attachEvent("onclick", start);
}else if(btn.addEventListener){
  btn.removeEventListener("click", stop, true);
  btn.addEventListener("click", start , true);
}

It all works fine in FF and Chrome. I have switched the order of attach/detach, just to see if it makes a difference, but it doesn't.

Addendum Sorry, and no answers involving jQuery, Protoype et al. Its not something I want to integrate for this project.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about event-handling