views:

39

answers:

1

i have this javascript code:

        var step = 8;                 // How many pixels to move per step
        var current = -1920;            // The current pixel row
        var imageWidth = 1920;        // Background image width
        var headerWidth = 960;        // How wide the header is.

        function slide_in(){
            //Go to next pixel row.
            current += step;

            //Set the CSS of the header.
            $('#bgfade').css("background-position",current+"px 0");

            if(current==0) alert('stop');
        }

        //Calls the scrolling function repeatedly
        $('#bgfade').click(function(){        
            var init = setInterval("slide_in()", 1);
        });

this makes the background slide. i want to exit when the var current is = 0, and let the background in that position.

thanks

A: 

You need to use clearInterval(), like this:

var step = 8;                 // How many pixels to move per step
var current = -1920;            // The current pixel row
var imageWidth = 1920;        // Background image width
var headerWidth = 960;        // How wide the header is.
var init;

function slide_in(){
    //Go to next pixel row.
    current += step;

    //Set the CSS of the header.
    $('#bgfade').css("background-position",current+"px 0");

    if(current==0) clearInterval(init);
}

//Calls the scrolling function repeatedly
$('#bgfade').click(function(){        
    init = setInterval(slide_in, 1);
});

The other changes here are the scope, so the timer ID is available to the other function, as well as not passing a string to setInterval() to avoid any other potential issues.

Nick Craver
thanks, this works but i cannot link another action in the sequence? i clone the function to make the contrary but they don't work one after the other
TrustWeb
@TrustWeb - I'm not following, can you explain that comment a little more?, what are you trying to do?
Nick Craver
@Nick Craver - ok, sorry. I wanto to slide_in, perform actions and slide_out. i call the second function like the first but the first is missing. init = setInterval(slide_in, 1); alert('hi'); outinit = setInterval(slide_out, 1);
TrustWeb