Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML 5 independent Scrolling for perspective illusion

Tags:

html

scroll

Is there some sample HTML code that establishes the following effect:

There is a foreground layer, containing text and images. Then there is a background layer, displaying an image,

When the user scrolls the page, the foreground scrolls at regular speed, but the background with a lower speed.

This would create a Flintstones-like faux perspective.

like image 244
Sjakelien Avatar asked Mar 02 '11 14:03

Sjakelien


2 Answers

This "faux perspective" you're talking about is called parallax.

There are a number of demos available online

  • http://webdev.stephband.info/parallax.html
  • http://dev.jonraasch.com/scrolling-parallax/examples/scrolling-parallax

I would suggest using a background image on body with background-attachment: fixed and then set a short timer to check the page scroll length.

On every update of the timer, detect the scroll length, and multiply it by a modifier (say 0.1), set this new value as the background-position:

$body = $('body');

function parallax()
{
  var pageOffsetX, pageOffsetY, modifiedOffsetX, modifiedOffsetY;

  pageOffsetX = ...//get the offset
  pageOffsetY = ...//get the offset
  modifiedOffsetX = pageOffsetX * 0.1;
  modifiedOffsetY = pageOffsetY * 0.1;

  $body.css('background-position', modifiedOffsetX + 'px ' + modifiedOffsetY + 'px');
  setTimeout(parallax, 100);
}

parallax();

The modifier is how much the background should move for every px the user scrolls. You may need to adjust the offsets if your background shouldn't repeat, and you may need to negate the offset depending on how you get the pageOffset values.

Adjusting the timeout will change the responsiveness of the background. You may be able to capture a mouse scroll event, but you'll also have to check if a user has jumped down the page via a link, etc.

like image 198
zzzzBov Avatar answered Nov 12 '22 14:11

zzzzBov


The way I would accomplish this is first by setting background: fixed for the page, and then constantly polling the page to determine whether the window.pageYOffset value has changed [1]. If it has changed, you can then move the background image up or down by (half|one third|one fourth|whatever) that amount, to mimic the effect you're talking about.

I'm not going to try to code this up, but I would be very interested to see your result.

[1] Note: Do NOT do this by attaching an event to the pagescroll event, as doing so can seriously screw up most browsers, as twitter learned the hard way.

like image 23
eykanal Avatar answered Nov 12 '22 14:11

eykanal