Now, let's add in the code that'll make our background animate when we scroll down the page.
Add the following code to our anonymous function so we can get this script off the ground and running:
$(window).scroll(function() { var yPos = -($(window).scrollTop() / 2); $(".row").css({ backgroundPosition: "50% " + yPos + "px" }); });
Here's a screenshot illustration of how our script will function when previewed in the browser:
We used a window scroll function here because we want to trigger our code every time our user scrolls through the window using the mouse wheel or the browser's scroll bar.
Our variable, yPos
, is set to a negative value because we want the background animation to move in the same direction as the page elements that are being scrolled. Using scrollTop()
gives us the current vertical scrollbar position of window
. We then divide that number by two.
We use the css()
method to set our background position....