runner

by kidastudio

HTML

<div class="holder"><div class="runner"></div><br/>
    <div class="track"></div></div><br/>
<button type="button" id="faster">Faster</button>
<button type="button" id="slower">Slower</button>
<span id="delay"></span>

CSS

.runner {
    margin-top: 100px;
    width: 266.666px;
    height: 200px;
    background: url('http://stephino.com/runner.png') no-repeat 0 0 transparent;
}

.track {
    margin-top: -50px;
    width:100%; 
    height:20px; 
    background: orange;
}

.holder {
    overflow: hidden;
}
}

JavaScript

var runner = $('.runner');
var steps = 24;
var currentStep = 0;
var delay = 35;
var trackLength = 600;

var nextStep = function() {
    // Move the background
    runner.css('backgroundPosition', '-' + (6400/24 * currentStep) + 'px 0px');

    runner.css('marginLeft', '' + trackLength + 'px');
    
    // Increment the step
    currentStep++;
    trackLength -= 15;
    
    // End reached
    if (currentStep >= steps) {
        currentStep = 0;
    }
    
    if(trackLength < -267) {
    	trackLength = 600;
    }
    
    // After one second, call self
    window.setTimeout(nextStep, delay);
};

nextStep();

// Buttons
$('#faster').click(function(){
    delay -= 1;
    if (delay <= 0) {
        delay = 1;
        $(this).fadeOut();
    }
    $('#delay').html(delay);
});
$('#slower').click(function(){
    delay += 1;
    if (delay >= 2) {
        $('#faster').fadeIn();
    }
    $('#delay').html(delay);
});

// First-time
$('#delay').html(delay);