Javascript: jParallax - Interactive Positioning w/ jQuery

Oct 6th, 2008 by admin

jparallax.jpg

What does jParallax do?

Parallax turns a selected element into a ‘window’, or viewport, and all its children into absolutely positioned layers that can be seen through the viewport. These layers move in response to the mouse, and, depending on their dimensions (and options for layer initialisation), they move by different amounts, in a parallaxy kind of way.

Diagram of parallax layers.

The diagram on the right illustrates what Parallax does to the html:

<ul id=“parallax”>

    <li></li>

    <li></li>

  </ul>

Here’s a demonstration with some images:

But that’s not all that Parallax does. If the layers are made of <div>s or <li>s or any other container then content can be positioned inside those layers, and Parallax provides methods for navigating to that content in response to user events.

More Examples

Using jParallax

The default behaviour of jParallax is to show the whole width of a layer in response to the mouse travelling the whole width of the parallax ‘window’. When the mouse is moved to the extreme left-hand side of the parallaxed window the left-hand side of the layer meets it, and when the mouse is moved to the extreme right-hand side of the parallaxed window the right-hand side of the layer arrives at the right hand-side of the window.

The simplest way to use jParallax is to make the layers different sizes using CSS. Bigger layers move faster and thus appear closer, and unless a layer is smaller than the viewport, its edges are never seen. The Colour Drops Demo was made in exactly this way, with jParallax in its default state, and the ’speed’ of the layers controlled simply by making the images different sizes. No options have been passed in.

However, we all want tweaky-tweaky. I also give you tweaky-tweaky…

Instantiation

jQuery(‘#parallax’).jparallax(options, layer_options);

Clearly the parallaxed element(s) can be selected any way you like. For the sake of simplicity for the rest of this guide I refer to the parallaxed element as ‘#parallax’.

CSS

In most cases, you should set the following CSS on the parallaxed element:

#parallax

    {position:relative; overflow:hidden; width:npx; height:npx;}

Children of a parallaxed element become layers, and are automatically given position:absolute; in order to start moving them around, but the parallaxed element itself needs position:relative; or position:absolute; or the layers will move relative to the document rather than the viewport. overflow:hidden; stops layers displaying outside of the bounds of the viewport, and width and height should be set to prevent the viewport collapsing.

In addition, jParallax needs to know how big layers are, and if there is anchored content inside a layer it needs to know where and how big it is. It uses jQuery’s height(), width() and offset() methods to find out. However, if you experience trouble with the range of motion of a layer you should consider setting all dimensions (height, width, top and left) explicitly via CSS to make life easy for those methods.

Options default values

The following options can be passed to jParallax to set the behaviour of the mouse, default behaviour of the layers, animation settings and so on:

mouseResponse: boolean true
mouseport: jQuery(’element’) same as parallaxed element
Enables mouse response and specifies the DOM element to track the mouse in. By default it’s on, and it’s the same as the viewport, the DOM element that you instantiated jParallax on. Perhaps you might want to use the whole window as the mouseport, in which case you could pass in jQuery(window).
triggerResponse: boolean true
Enables response to ‘jparallax’ events triggered on the parallaxed element(s). Content containing an anchor tag, and positioned inside a layer, is pulled to the centre of the viewport when the anchor’s name attribute is passed as the first value in an array via the custom ‘jparallax’ event. Consider the following code:

jQuery(‘a’).click(function(){

      var ref=jQuery(this).attr(“href”);

      jQuery(‘#parallax’).trigger(“jparallax”, [ref]);

      });

This says that when an anchor in the document is clicked, its html attribute will be passed as a ref to the element ‘#parallax’ in a ‘jparallax’ event trigger. If there is content on one of the layers containing <a name=”ref”> it will be pulled to the centre of the viewport. If not, nothing will happen. If triggered content is not being used switching triggerResponse to false will save the browser a tiny amount of overhead on initialisation of the plugin.

triggerExposesEdges: boolean false
Sets whether triggerResponse pulls the edges of layers into the viewport while attempting to display content in the centre.
takeoverFactor: 0-1 0.68
takeoverThresh: 0-1 0.002
Sets the speed and accuracy with which the layers ‘catch up’ with the mouse position when the mouse enters the mouseport from somewhere other from whence it has left. Technically, takeoverFactor is the decay of the approach curve per animation frame, where lower numbers are more decay (and therefore quicker), and takeoverThresh is the distance within which the layer position is considered to have arrived, as a ratio of the mouseport dimension. takeoverThresh is by default a five-hundredth of the mouseport - larger numbers may produce a noticeable ‘jump’ at the beginning of a new mouse movement. You shouldn’t need to mess with these too much, I just stuck them in there because we all like tweaky-tweaky.
frameDuration: milliseconds 25
You may want to put this up to save CPU. About 40 is acceptable (25 frames/second). I like it zippy, though. I hear Google Chrome has got timing accuracy down to 1ms! Others don’t do lower than 15ms.
xparallax: boolean true
yparallax: boolean true
xorigin: ‘left’ | ‘centre’, ‘center’, ‘middle’ | ‘right’ | 0-1 ‘centre’
yorigin: ‘top’ | ‘centre’, ‘center’, ‘middle’ | ‘bottom’ | 0-1 ‘centre’
Sets default alignment of layers. See ‘Layer Options’ below for a detailed description.

Layer Options default values

In addition options can be passed to each layer individually. Layer options are passed as extra arguments:

jQuery(‘element’).jparallax(options, layer_0_options, layer_1_options, etc.);

As an example, to give the second layer a set xtravel value, but pass no options as default:

jQuery(‘element’).jparallax({}, {}, {xtravel: ‘200px’});

A layer option object can have the following parameters:

xparallax: boolean true
yparallax: boolean true
Enables motion in the x or y direction in response to the mouse.
xtravel: 0-1 | ‘n%’ | ‘npx’ 1
ytravel: 0-1 | ‘n%’ | ‘npx’ 1
When specified as a number between 0 and 1, or as a percentage string, xtravel and ytravel scale the distance a layer will travel. When specified as a pixel string they set the distance a layer will travel.When travel is left at the default 1, the behaviour is to display the whole width of the layer over the whole range of the viewport in response to the mouse travelling the whole width of the mouseport. In other words, the left meets the left when the mouse is on the left, the centre lines up when the mouse is at the centre and the right meets the right when the mouse is at the right. Setting xtravel to, say, 0.5, or '50%' will mean half that layer’s possible horizontal travel will occur over the same range of mouse motion.Numbers outside the range 0-1 can be used, too. Negatives will cause travel in reverse direction, scaling factors greater than 1 (or '100%'), or less than -1 (or '-100%') will cause the edges of layers to be pulled into view.

xorigin: ‘left’ | ‘centre’, ‘center’, ‘middle’ | ‘right’ | 0-1 ‘centre’
yorigin: ‘top’ | ‘centre’, ‘center’, ‘middle’ | ‘bottom’ | 0-1 ‘centre’
Only meaningful when xtravel or ytravel are not 1. Determines which point of the layer lines up with which point of the viewport when the mouse is at that point in the mouseport. Got that?Look, if origin.x is set to ‘left’, then when the mouse is moved to the left hand side of the mouseport the left hand side of the layer arrives at the left hand side of the viewport. If it’s set to ‘centre’, then when the mouse is at the centre of the mouseport the centre of the layer is aligned with the centre of the viewport. Similarly with ‘right’.Numbers may also be used:

  • 0 is equivalent to ‘left’.
  • 0.5 is equivalent to ‘centre’ or ‘center’ or ‘middle’.
  • 1 is equivalent to ‘right’.

Numbers outside the range 0-1 may also be used, although you will start seeing the edges of layers appearing inside the viewport. And they’ll travel in the opposite direction.

Tips

Extra graphics

If you want to add elements to #parallax, such as overlaying curved corner images like in the above example, add them after you have instantiated jParallax in order to avoid having those elements included in the calculations.

Other Resources

Future features

  • Freeze, to enable position to ’stick’ and be ‘unstuck’ by user trigger.

Version history

0.9.1 (Not released.)

  • Fixed bug when specifying travel by %.
  • Travel px or % detection has more robust Regex.

0.9

  • Code optimisation.

0.8.1

  • Tested in Safari, Firefox 3, IE6, IE7, Google Chrome (Beta) and Opera 9.5. IE6 has trouble handling multiple jParallax instances when they are declared on one jQuery selector. Other than that, all present and correct. Declare your doctypes!
  • Bug fixed in matrixSearch.

0.8

  • Gracefully handles window resize.
  • Begins to shoot for proper IE support.
  • Positioning algorithm re-written. In fact, it can barely be called an algorithm any longer, as the positioning now relies almost solely on CSS. Whereas previously it was defined absolutely in pixels, positioning is now defined by percentage combined with variable (negative) margins, forcing the browser CSS engine to take more responsibility for re-positioning. This means that window resizing is smooth, and the Javascript has less calculating to do. However, it may be more of a CPU hog this way. Some testing will be done.
  • Due to the above changes, some Options and Layer Options now mean something slightly different to their original definitions. For example, xtravel is now a ratio by default rather than a pixel definition.
  • Made a minor change to the way dimensions are registered - they now use the jQuery methods width(), height() and offset(), so they should no longer need to be explicitly set via CSS (although it wouldn’t hurt, if you want to be sure). This also applies to layer contents.
  • Added Target Demo to demonstrate window resizing and Trigger Response, and updated arse demo to jParallax.
  • Some code optimising to make it faster, but there’s more that can be done in this department.
  • Docs updated.

0.7 (Not released)

  • Unreleased. Broken.

0.6

  • Trigger response added.
  • New demos added. Remote control and a crude trigger demo.
  • Options simplified. They were getting a bit out of hand. Default options are now all attributes of one object, rather than nested objects as previously. (Layer Options still work the same way, one object per layer).
  • Docs updated.

0.5

  • Soft Takeover animation timer and mouseport detection rewritten to get rid of jerky re-entry bugs. Life is now smoother and creamier.

0.4

  • Based on an idea I read somewhere on the web or possibly in the book jQuery In Action, jParallax now saves CPU by moving the layers at a maximum frameRate and not on every change of mouse co-ordinates.
  • Soft Takeover animates layers to position over time on mouseport re-entry. It’s a little dodgy.

0.3

  • Implemented a crude Soft Takeover. It doesn’t animate to position over time, just over mouse move, but it does make the mouseport entry a bit smoother.

0.2

  • Fixed xtravel, ytravel and mouseport initialisation.
  • Added Stalk Button demo.

0.1

  • Initial port from proof of concept code. My first jQuery plugin!
  • Colour drop demo.

Posted in Javascript |

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

eXTReMe Tracker