Parallax Website Design using CSS & jQuery

Designers | Programmers

parallexIf you haven’t heard of Parallax website design, check out the post from Monday : Design Critique: Sevenly

This dimensional designing, where one area of the website looks like it is closer/further away then another section, is becoming increasingly popular. It is remarkably easy to create this illusion using CSS and jQuery.

The Illusion

The illusion is created by changing the scrolling rate of a Div. So one object, say the text, is left scrolling at the normal rate, while the background scrolls slowly, and the image in the front scrolls quickly.

So to do this, we need to control how quickly things scroll in connection to the scrollbar moving.

The CSS

Starting with a text Div, add the following CSS:

#text { position:fixed; }

This essentially removes all the scrollbar control over that Div. Normally, this Div’s fixed position will base itself on the window. So if you add:

#text { position:fixed; top:100px; right:200px; }

That div will align itself to the window – 100 pixels from the top, and 200 pixels from the right.

If, however, you put it inside another Div, perhaps called “outline”, and give that Div the following coding:

#outline { position:relative; margin:0px auto; width:1000px; }

Because Outline Div has a “position:relative;” set, the Text Div will align itself inside of that Div.

The jQuery

Now that we’ve removed the ability of the scrollbar to control that Div, let’s give it the control we want it to have:

$(window).bind('scroll',function(e){
parallaxScroll();
});

 

function parallaxScroll(){
var scrolled = $(window).scrollTop();
$('#text').css('top',(100-(scrolled*1.1))+'px');
}

The first section binds the window scrolling action to a function called “parallaxScroll”. So anytime you scroll, that function takes place.

The second section is our function. That’s where the magic happens. We set a variable, “scrolled”, to the amount the window is from the top. “scrollTop()” is a built-in jQuery function for finding the distance you’ve scrolled from the top of the window.

Next, we reference the Div we’re editing, “#text”, and set the CSS property “top” to the distance we want. Here’s the explanation of the math there:

100 is the original distance from the Top that we set in the CSS. This is where the Div will start the scrolling. If you change the CSS, but don’t change this number, you won’t see a difference when you start scrolling.

scrolled*1.1 – this takes the distance from the top and multiples it by 1.1. Therefore, the higher this number, the faster that Div will scroll. The lower the number, the slower it will scroll. The number “1” will equal a normal scrolling amount. “.5” would be half the scrolling speed, “2” will be double the scrolling speed.

Finally, we add the “px” to number so that it will work.

The Result

Accolades of your friends, family, coworkers!

Or maybe just a really cool website.

Comments