user993683
user993683

Reputation:

Horizontal scrolling background-image with jQuery

Here's my attempt at the jQuery:

$(document).ready(function(){
$('#bg').animate({ backgroundPosition: '320px 0px'}, 10000, 'linear');
});

Here's CSS for bg:

#bg {
    background: url('scribbles.png') repeat-x 320px 0px;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

Here's the HTML:

<div id="bg"></div>

I want the background image to move across the screen slowly. Any suggestions?

Thanks!

Upvotes: 2

Views: 4292

Answers (2)

vee
vee

Reputation: 1246

Is the image to continue scrolling forever? If not, the the following may be a good starting point:

$('#bg').animate({ backgroundPosition: '+=100% 0px'}, 10000, 'linear');

If it is to repeat forever, then consider the following solution with a recursive call-back:

var animateBackground = function()
{
    $('#bg').animate
    (
        { 
            backgroundPosition: '-=100px 0px'
        }, 
        10000,
        'linear',
        function()
        {
            animateBackground(); // recursive call back
        }
    )
};

$( // short-hand for "$(document).ready"
    function()
    {
        animateBackground(); // initial call that starts everything off
    }
);

Upvotes: 3

sha256
sha256

Reputation: 3099

Background position is same for the both css & jquery cases. They should be different. Unless why would it move? Set a previous position in css & give the final position in the jquery part of the code. It'd work!

Upvotes: 1

Related Questions