views:

35

answers:

1

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.

+1  A: 

You should probably use a toggle method instead : http://jsfiddle.net/QRYsS/

// get a cross-browser function for adding events, place this in [global] or somewhere you can access it
var on = (function(){
    if (window.addEventListener) {
        return function(target, type, listener){
            target.addEventListener(type, listener, false);
        };
    }
    else {
        return function(object, sEvent, fpNotify){
            object.attachEvent("on" + sEvent, fpNotify);
        };
    }
}());

var toggle = (function(){
    var state = false;
    return function(){
        state = !state;
        if (state) {
            alert("foo");
        }else{
            alert("bar");
        }
    };
})();

on(btn, "click", toggle);
Sean Kinsey