views:

118

answers:

2

I have the following code, and it works fine until i hit the the #play button. I'm assuming it's because the var intID is set in another place and it's not in the same scope when i window.clearInterval() it... how do I fix this? BTW, this is the Google Maps API Version 3

  function intervalTrigger(){
        return window.setInterval(function(){
            placement++;
            if(placement >= markers.length){placement = 0;}
            google.maps.event.trigger(markers[placement], "click");
        }, 5000);
    };

    var intID = intervalTrigger();

    $('#map_canvas').click(function(){window.clearInterval(intID);});

    $('a[href=#nextmarker]').live('click',function(){
        placement++;
        if(placement >= markers.length){placement = 0};
        google.maps.event.trigger(markers[placement], "click");
        window.clearInterval(intID);
        $('a[href=#pause]').replaceWith('<a href="#play">Play</a>');
        return false;
    });
    $('a[href=#prevmarker]').live('click',function(){
        placement--;
        if(placement == -1){placement = markers.length-1}
        google.maps.event.trigger(markers[placement], "click");
        window.clearInterval(intID);
        $('a[href=#pause]').replaceWith('<a href="#play">Play</a>');
        return false;
    });
    $('a[href=#play]').live('click',function(){
        $('a[href=#play]').replaceWith('<a href="#pause">Pause</a>');
        var intID = intervalTrigger();
        return false;
    });
    $('a[href=#pause]').live('click',function(){
        window.clearInterval(intID);
        $('a[href=#pause]').replaceWith('<a href="#play">Play</a>');
        return false;
    });
+1  A: 

You're creating a new variable with that var keyword, if you want to reference the variable in the outer scope, you need to take it out, like this:

$('a[href=#play]').live('click',function(){
    $('a[href=#play]').replaceWith('<a href="#pause">Pause</a>');
    intID = intervalTrigger();
    return false;
});

Otherwise it's just creating a new variable inside that .live() handler that doesn't go anywhere...but since you want to set the variable you already have, leave off the var.

Nick Craver
+1  A: 

Remove the var from your #play click handler to the following:

$('a[href=#play]').live('click',function(){
    $('a[href=#play]').replaceWith('<a href="#pause">Pause</a>');
    intID = intervalTrigger();
    return false;
});

That will correctly set the value of the global var intID so it's available to the other event handlers.

Pat