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?
Look here to see an example of how far the user has scrolled on the page. See the
$(this).scrollTop()
?Rather than referencing $(this), try using the background div. Then use a .scroll function to determine how much to move the background.
Your code should look something sort of like this:
I don't think you can use += or -= when you have two parts in the CSS. There is something you can do, it is a bit tricky but it works:
This code gets only the second number from the background-position of the div (the top position), converts it to int, and increases it by 10. Then it just animates the div to the new position.
If you don't want to be hassled with the extra background div, here's my code I wrapped up from several examples:
The Math.max is required for cross-browser issues. Also replace '1920' with the width of your background image
This worked for me:
In js:
In css:
Where #main is the div whose background image I wanted to move. No need to have height: 100% for html, body.
This is a variation for multiple background images.
Here you go. Background is set to 10% scroll. You can change the background scroll rate by changing the 10 in the code.
CSS
JavaScript
Check working example at http://jsfiddle.net/Vbtts/
Click this link for the full screen example: http://jsfiddle.net/Vbtts/embedded/result/
This might do it: