5

This is my first time on Stack Overflow, so I apologize if my question is a bit verbose. I have a bit of a quandary:

I want to create this parallax-scrolling effect where the background image (the height of which is larger than that of the window) always scrolls in direct relationship to your progress on the page.

For example, when you've scrolled 25% of the way down the page, the background image should have scrolled by 25%. And when you've scrolled to the very bottom of the page (100%), the background image should have scrolled to its bottom as well (100%).

With this parallax effect, the background image would still scroll, but it wouldn't tile or need to be stretched. However, with my current code (show below), the background does scroll much at a much slower rate than the content on the page; however it eventually reaches the bottom of the background and starts tiling.

I feel like I'm missing something mathematically. Any ideas?

Here's the jQuery I'm using:

NOTE: the background image has a height of 1200px

$(window).scroll(function() {
    var x = $(this).scrollTop(); /* Scroll Position */
    var y = $('html').height(); /* Height of Page */
    var z = x / y; /* Progress of current position on page */
    $('html').css('background-position', '0% ' + (z * 1200) + 'px');
});

EDIT: I figured out the issue: Just as you don't start scrolling a page until you're at the bottom of the viewport, I shouldn't start scrolling the background image until that point either. So what I need now is a new function. If r is the viewport height, the function shouldn't move the background image down for the first r pixels when scrolling down, and it shouldn't move the background image up for the last r pixels when scrolling up. Boy, this is turning into a real parallax-scrolling project. Any suggestions?

user3553106
  • 69
  • 1
  • 5

1 Answers1

0

I think this is what you were going for:

$(window).scroll(function() {
  var scrollPos = $(this).scrollTop();
  var pageHeight = $(document).height() - $(this).height();
  var progress = scrollPos / pageHeight;
  var backgroundOffset = (progress*100) + '%';
  $("html").css("background-position", "0% " + backgroundOffset);
});

See demo