Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery on window scroll animate background image position

I am trying to achieve a scrolling effect using jQuery. I have a background div set to 100% browser window size with overflow hidden. This has a large background image that is approx. 1500px x 2000px.

The effect I want is when the user scrolls down the page the background image moves at a percentage of the scrolled distance, so for every 200px scrolled down the page the image moves 10px in the same direction.

Can anyone point me in the right direction? Is this even possible? : ) Many thanks in advance.

UPDATE

I have since tried variations on the suggestion by @Capt Otis but I'm still struggling the code I am playing around with is as follows:

$(window).scroll(function(){
    if($(this).scrollTop() > 200) {
        $('#div').animate({'background-postion': '+=10px 0'}, 500);
    }
});     

Can anyone shed any light on what I am doing wrong?

like image 723
mtwallet Avatar asked Feb 15 '11 08:02

mtwallet


1 Answers

Here you go. Background is set to 10% scroll. You can change the background scroll rate by changing the 10 in the code.

CSS

html, body{
    height:100%;
    min-height:100%;
    margin:0;
    padding:0;
}
.bg{
    width:100%;
    height:100%;
    background: #fff url(..) no-repeat fixed 0 0;
    overflow:auto;
}

<div class="bg">
   <span>..</span>
</div>

JavaScript

$('.bg').scroll(function() {
    var x = $(this).scrollTop();
    $(this).css('background-position', '0% ' + parseInt(-x / 10) + 'px');
});

Check working example at http://jsfiddle.net/Vbtts/
Click this link for the full screen example: http://jsfiddle.net/Vbtts/embedded/result/


like image 176
Hussein Avatar answered Sep 20 '22 22:09

Hussein