JQuery powered parallaxing

Related tags

Scroll plax
Overview

Plax is on the backburner and is provided as-is. I won't be adding bug fixes or future improvements at this time. Plax is old enough that there are better options available so go forth an parallax!

Plax

Plax is a jQuery plugin that makes it suuuuuper easy to parallax elements in your site based on mouse position. You can see it implemented in many places throughout GitHub, including the 404 page, the 500 page, and the about page. I've also used a modified version to parallax a URL.

Dependencies

jQuery

Usage

Plax Demo

In the <head> of your document, link both jQuery and plax.

<script type="text/javascript" src="/js/jquery.min.js"></script>
<script type="text/javascript" src="/js/plax.js"></script>

Then in your javascript, add each "layer" to the list of layers to be parallaxed. Once that's done, enable Plax and you're good to go.

$('#plax-octocat').plaxify({"xRange":40,"yRange":40})
$('#plax-earth').plaxify({"xRange":20,"yRange":20,"invert":true})
$('#plax-bg').plaxify({"xRange":10,"yRange":10,"invert":true})
$.plax.enable()

Another way is to specify the arguments as data attributes on the layer elements.

<img src="octocat.png" data-xrange="40" data-yrange="40">
<img src="earth.png" data-xrange="20" data-yrange="20">
<img src="bg.png" data-xrange="10" data-yrange="10" data-invert="true">

Then plaxify them in bulk.

$('img').plaxify()
$.plax.enable()

If you would like your elements to parallax only when a certain element is moused over, you need to supply an argument to enable()

$.plax.enable({ "activityTarget": $('#myPlaxDiv')})

You can dynamically redefine the range of a layer by running plaxify() on it again. If the id matches another id in the layer array, it will replace it with the new range.

$('#plax-octocat').plaxify({"xRange":40,"yRange":40})
$('#plax-earth').plaxify({"xRange":20,"yRange":20,"invert":true})
$('#plax-bg').plaxify({"xRange":10,"yRange":10,"invert":true})
$.plax.enable()

$('#my-btn').click(function(){
  // bigger range
  $('#plax-octocat').plaxify({"xRange":200,"yRange":200})
})

Documentation

plaxify()

Add an item to the list of parallaxing layers. Ranges are centered at the items start location. For example, an item with a 20px range will be able to move 10px forward and 10px backward from its start location.

Parameters

xRangeinteger: is the distance across the x-axis the object will travel.

yRangeinteger: is the distance across the y-axis the object will travel.

invertboolean: (optional) inverting will invert the direction the object will travel across each axis.*

* The same effect can be achieved by providing xRange and yRange with negative numbers, making it possible to invert only a single axis.

useTransformboolean: (optional) defaults - true. When supported translate3d will be used rather than top and left*

enable()

Enable parallaxing.

Parameters

activityTargetObject: (optional) sets a specific DOM element over which Plax will track the mouse.

gyroRangeInteger / Float: (optional) sets the degrees of tilt needed to reach full movement in one direction, from the center position. For the full range, two times the degrees tilt is needed. Default value: 30.

disable()

Disable parallaxing.

Parameters

restorePositionsBoolean: (optional) resets all previously defined layers to their original positions when plax is deactivated.

clearLayersBoolean: (optional) clears all previously defined layers when disabling.

Best Practices

  • Items should be absolutely positioned, with top: and left: values specified.

  • If you plan to parallax a background plane, be sure to give it enough extra "bleed" room so the image stays behind it's frame at all times. Usually your bleed on one side should be equal to half the range you give it, though you can give it more if you are paranoid.

  • For more realistic parallaxing (see "how to do the math" below), pick an "anchor object". Base your ranges for each object on the anchor object's range, getting exponentially larger the farther it is supposed to be from the anchor object. For example, an object close to your anchor object might have 2x its range, while an object really far away may have 5x as big a range.

  • Objects that appear behind the anchor object should have invert set to true.

How To Fake It

Here are a couple real-life examples of parallaxing and a quick description of how you might emulate it with Plax.

Example #1

Picture driving down the highway. There are three objects: You, in the inside lane, a truck in the outside lane, and a sign on the side of the road. As you drive past the truck, the sign always manages to stay just out of view behind the truck.

The lesson

In this case, the truck becomes the "anchor", as it stays relatively still. It is the item upon which all the movement is based. If you were to recreate this scenario in your javascript, the truck would have a small range, say 10–20 pixels. That way, it would move a little, but not too much. Since the car you are in is moving faster relative to the truck it would need a larger range like 50–100 pixels. Finally, the sign, since it is "behind" the truck, will need to have invert set to true. Any object behind the "anchor" object should be inverted. Assuming the sign is always about the same distance from the truck as you are (the scenario where you never actually see the sign) then its range should also be around 50–100 pixels.

Example #2

Picture another driving scenario. You're the passenger in a car driving past a barn. In the distance you can see mountains. If you look at the grass on the side of the road, it seems to be flying by at blazing speed. If you look at the barn, it still appears to be passing by, but much more slowly than the grass. If you look to the mountains in the distance, they pretty much seem to be staying where they are at.

The lesson

The principals from the previous scenario are still present in this situation, only the anchor has moved to the back layer (the mountains). Since the mountains are far off in the distance and barely moving, they get a range of 5–10 pixels. Each layer as it comes forward should have a greater range than the layer before it. The barn would probably have 20–30 pixels of range and the grass near the road would probably have 100 pixels of range.

Comments
  • Plax Responsive-ness

    Plax Responsive-ness

    Hi Cameron,

    Firstly, what a champion plugin, possibly one of my favorite jQuery plugins. I am currently building my portfolio, implementing your plugin. And everything is going great.

    This isn't as much of an issue as it is rather a request on some advise.

    I'm trying to make the site responsive using css mediaqueries, but struggled to get the layers to update on resize() - I managed to get it to work when refreshed on an already resized window. But wanted to get it to work dynamically/instantly while resizing... anyway long story short...

    I managed to achieve this by passing a function to on resize event - like so...

    function disablePlax(){ $.plax.disable({ "clearLayers": true }) $('img.js-plaxify[style]').css('top', ''); $('img.js-plaxify[style]').css('left', ''); $('div.js-plaxify[style]').css('top', ''); $('div.js-plaxify[style]').css('left', ''); }

    and then start it up again, by calling the same function(s) called in document ready, like this:

    function enablePlax(){ var layers = $('.js-plaxify') $.each(layers, function(index, layer){ $(layer).plaxify({ xRange: $(layer).data('xrange') || 0, yRange: $(layer).data('yrange') || 0, invert: $(layer).data('invert') || false }) })

        $.plax.enable();
    

    }

    I am a complete noob to jQuery, and am not sure if this is the best way to handle this sort of thing, but wanted to know if there was a better way of doing this. Or is it a case of "Don't fix if its not broken"?

    Thanks again for Plax

    opened by jaredrethman 10
  • Support3d transform

    Support3d transform

    I was just implementing this with some pretty large image layers. And using top/left to move elements was pretty jolty.

    I've added support for using translate3d rather than top/left where it is supported. Default to true. * This does however require a bump in jQuery dependency support to 1.8.0+

    I've also implemented an option, allowing for use of this, on plax layers contained within fixed elements. Currently if the plax layer is a fixed element, and following scroll it would be calculated as outside the viewport, movement is stopped even though it is still visible. I've added an option to declare that the plax is fixed - and continue it's movement.

    Updated all examples to use jQuery 1.8.0, bower.json, and README to document the 2 additional options above.

    opened by craigblagg 9
  • Installing with ender fails

    Installing with ender fails

    $ ender add plax
    Welcome to ENDER - The no-library library
    -----------------------------------------
    installing packages: "plax"...
    this can take a minute...
    something went wrong install your packags!
    

    I've got up-to-date versions of node, npm, and ender. Other ender modules install without any problems.

    opened by djbender 7
  • Add option for restoring the original positions upon disable.

    Add option for restoring the original positions upon disable.

    This is quite useful when your page has multiple sections where you won't be seeing all of them at the same time.

    In this case you wouldn't want the entire set of plax layers to be enabled all the time, and as such the clearLayers option is great.

    However, moving back and forth from different sections of the page, there's a risk the objects aren't in their original position when clearing the layers, and when moving back and re-enabling plax on them, they would get a new initial position, which would be stacking up for each time you move back and forth to the section.

    New option simply makes sure that each layer's original position is restored upon disable, normally combined with clearLayers, but there are possible uses without clearing the layers as well.

    opened by magebarf 6
  • Disable motion detection by default on desktop

    Disable motion detection by default on desktop

    This isn't perfect, but it changes how Plax works by default on desktop. Previously it would always be enabled if the browser supported it (Firefox only?). Now it will be disabled unless you explicitly allow desktop support. Detection is done by detecting 'ontouchstart' which is only on mobile (for now).

    opened by zpao 5
  • Won't work in Firefox?

    Won't work in Firefox?

    Hi,

    I viewed your demo (On your personal blog) using Firefox and the effects works great. I download the kit, added it to a test page that I am building, but the images don't move. Your kit demo's also don't move using Firefox. I uploaded the test page here: http://www.inspiredworx.com/dev/octavius/index2.html

    Could you shed some light on this for me please?

    Thanks.

    opened by huwrowlands 5
  • Allow background position animation, support right/bottom positions, use inversion factor in calculations, allow repeated init of elements without ID attribute

    Allow background position animation, support right/bottom positions, use inversion factor in calculations, allow repeated init of elements without ID attribute

    Flag "background" can be set to animate background-position instead of element position (only allows pixel values, 0% and top/left, the rest is too complex/slow to compute due to how "100%" makes the background stick to the right/bottom of the container).

    If the element was positioned using properties "right" or "bottom", then we make sure that those properties continue to be used for changing position.

    ID attributes were used before to check if an element already is in the list of elements to work on, now compares DOM elements instead so no "id" attribute must exist.

    Inversion factor cleans up the code a little :)

    opened by dzuelke 5
  • Jitter in FF 14 on Mac

    Jitter in FF 14 on Mac

    This is potentially a browser issue as it was working fine before the FF 14 update yesterday, however the plax effect is very jittery, even when the browser does not have focus.

    If you look at the github 404 page in FF 14 on a Mac you will see the issue we are seeing on our site(s).

    opened by Mviner04 4
  • Make PLAX work properly with bottom: and right: attributes

    Make PLAX work properly with bottom: and right: attributes

    Right now, PLAX doesn't handle these cases properly at all. There are lots of cases where bottom: and right: need to be used instead of top: and left:.

    opened by fletom 4
  • Store the actual starting positions.

    Store the actual starting positions.

    If mouse pointer is positioned at middle of screen when activating Plax, if there is any margin applied to any elements they will make a "leap" upon first plaxifier update.

    This seems to stem from the offsetLeft and offsetTop not taking the margin into consideration, which the jQuery .position() values does.

    Clearest example of this I've found is the GitHub error 500 page, where the "Ooops" text has a 10px margin defined. Positioning the mouse pointer near the middle of the page, and reloading the page, all elements but the text layer can be made to stay roughly in the same place, but the text layer will always make a jump, of roughly 10 pixels.

    opened by magebarf 3
  • Plax on elements loaded via ajax

    Plax on elements loaded via ajax

    Hi, I can't make plax to work on elements loaded via ajax.

    On document ready I have this code: $('.plax').plaxify(); $.plax.enable({ "activityTarget": $('footer')});

    Then before my ajax call i have this: $.plax.disable(true);

    And when the content is loaded i call again: $.plax.enable({ "activityTarget": $('footer')});

    Note:Ajax function completely destroys old plax elements and render new ones. Please can you advise? What am I doing wrong? Thanks in advance.for your answer!

    opened by hjujah 3
  • Plax + Turbolinks [It worcks]

    Plax + Turbolinks [It worcks]

    Hello, First of all, thanks so much for this awesome plugin. (Im really sad about the support ending).

    This is not realy an issue but I have try to run plax with Turbolinks. I cant find any explanation of how to do it. So I found it myself and I want to post the solution here :3

    ( function() {
    	Turbolinks.start();
    	var ready = function()
    	{
    		console.log( "🦄 TurboLinks Ready -> " + window.location.href + " width: " + $(window).width());
    		// PLAX
    		if( $('.yourPlaxSelector').length )
    		{
    			$('.yourPlaxSelector').plaxify();
    			$.plax.enable();
    		}
    	}
    	var cache = function()
    	{
    		console.log( "🦄 TurboLinks CacheLoad" );
    		// Allow plax function `inViewport` to worck properly.
    		// Without it Plax will only worck on the first call of `ready`.
    		$.plax.disable( { "clearLayers": true } );
    	}
    	// Turbolink tracker
    	var change = function()
    	{
    		console.log( "🦄 TurboLinks Change" );
    		window['referer'] = window.location.href;
    	}
    	ready();
    	document.addEventListener("turbolinks:before-cache", cache);
    	document.addEventListener("turbolinks:load", ready);
    	document.addEventListener("page:change", change);
    } )( jQuery );
    
    opened by Golgarud 0
  • chrome + plax 1.4.1 issue

    chrome + plax 1.4.1 issue

    Hello thanks for this plugin! I have an issue with plax 1.4.1 who doesn't work in chrome, I have an error line 262: "if (!inViewport(layers[0].obj[0].parentNode)) return;"

    it works well with others web browser or plax 1.3.1

    opened by yrollyou 0
  • Fix for document.body() being null

    Fix for document.body() being null

    That is in case you implement this: https://github.com/cameronmcefee/plax/issues/66#issuecomment-119740283 Or you could execute the script using

    $( document ).ready()
    

    in plax.js itself, which might be even better. Your call @cameronmcefee

    opened by energyuser 1
  • translate3d and overlays w/z-index (apparent in Safari)

    translate3d and overlays w/z-index (apparent in Safari)

    Before I dive in - just wanted to say thank you for an excellent plugin.

    Discovered something which may be useful to others and is possibly an issue with browser rendering of translate3d in certain circumstances (haven't dived in too deep....)

    When there is an element layer (1) positioned above the parallax wrapper layer (2), they are siblings, and layer 1 has a higher z-index then on a Safari that supports translate3d then layer 1's text color dims.

    I haven't tested to see whether other attributes like background color etc.. are affected by this. Seen on Safari 7.1

    Simple solution is to disable translate3d with the useTransform option.

    opened by shaiherman 1
  • I use a

    I use a "position: absolute" in a div "position: relative". Is does not work.

    Such as

    <div style="position: relative;bottom: 5em;left: 2px;">
      <a href="http://ze3kr.com/video/2014/07/12/s1/#video" title="Play">
        <img src="http://ze3kr.com/image/play.png" style="position: absolute;width: 72px;height: 72px;" class="js-plaxify" data-xrange="20" data-yrange="20" />
      </a>
    </div>
    
    var layers = $('.js-plaxify')
    
    $(document).ready(function () {
        $.plax.enable()
    })
    

    It's does not work. I find "inViewport" is wrong, When elements in the Viewport, it is not recognized. When I was at the top of the page (not the actual inViewport), but it is recognized inViewport.

    And I Change the HTML like that

    <div style="position: relative;bottom: 5em;left: 2px;" class="js-plaxify" data-xrange="20" data-yrange="20">
      <a href="http://ze3kr.com/video/2014/07/12/s1/#video" title="Play">
        <img src="http://ze3kr.com/image/play.png" style="position: absolute;width: 72px;height: 72px;"  />
      </a>
    </div>
    

    It still not work. But I find it Automatically add this

    div .js-plaxify {
      left: 173px;
      top: 936px;
    }
    

    At last, I add this and at finally it works.

    layer.obj.css('position', absolute);
    
    opened by ZE3kr 1
  • $.plax.disable() with non-default activity target

    $.plax.disable() with non-default activity target

    The disable function seems to use the window as the mouse movement listener. I have changed this to:

    disable: function(opts){
          plaxActivityTarget.unbind('mousemove.plax');
          ...
    

    This seems to work with my setup using the following options.

    $.plax.enable(
        { "activityTarget" : $('.phonecontainer') }
    );
    
    opened by lsei 1
jQuery plugin for creating interactive parallax effect

jquery.parallax What does jquery.parallax do? jquery.parallax turns nodes into absolutely positioned layers that move in response to the mouse. Depend

stephband 1.1k Nov 25, 2022
Largetable - jQuery plugin to scroll in/maximize large tables

largetable jQuery plugin to scroll in/maximize large tables Usage Install with npm: $ npm install largetable Then include largetable files in the HTM

Edinum 1 Feb 3, 2021
🚀 Scroll Follow Tab is a lightweight javascript library without jQuery, no dependencies.

Scroll Follow Tab is a lightweight javascript library without jQuery, no dependencies. It is used to make scrollspy effect for your menu, table of contents, etc. Only 21.7Kb.

Hieu Truong 11 Jun 20, 2022
🚀 Blazing Fast S3 Powered CDN ✨ Powered By Fastify, S3 Buckets & Docker!

?? WasiCDN Blazing Fast S3 Powered CDN, Powered By Fastify, S3 Compatible Buckets & Docker! Core DockerHub: https://hub.docker.com/r/maximking19/wasic

Maxim 5 Aug 31, 2022
A simple review gate powered by jQuery.

Review Gate Backstory Contracted to consult on digital strategy to help the client build stronger brand awareness/reputation across various platforms

David 2 Jan 18, 2022
Jquery.Circle.js - Circle is a Javascript global-menu library for jQuery.

Circle About Circle is a Javascript global-menu library for jQuery. Read more at the website: http://uc.gpgkd906.com/ Installation Just include the Ja

陈瀚 3 Jul 19, 2021
JQuery-TableToExcel - Light weight jQuery plugin for export HTML table to excel file

tableToExcel Light weight jQuery plugin for export table to excel file Demos Website and demo here: http://tanvirpro.com/all_project/jQueryTableToExce

Tanvir Sarker 4 May 8, 2022
Jquery-cropper - A jQuery plugin wrapper for Cropper.js.

jquery-cropper A jQuery plugin wrapper for Cropper.js. Demo Main dist/ ├── jquery-cropper.js (UMD) ├── jquery-cropper.min.js (UMD, compresse

Fengyuan Chen 653 Jan 7, 2023
JQuery charCounter - jQuery Character Counter Plugin

jQuery Character Counter A jQuery based character counter for <input> and <textarea> HTML tags. What is this? This simple plugin allows you to add a c

mmmm_lemon 1 Aug 10, 2022
Jquery.iocurve - jQuery plugin like Tone Curve on Photoshop or GIMP

jquery.iocurve jQuery plugin like Tone Curve on Photoshop or GIMP. See Official page for more information. Quick start Create HTML and open in your br

null 5 Jul 28, 2022
Jquery-actualizer - jQuery ajax actualizer

jQuery AJAX Actualizer Include jQuery & this plugin into your HTML file and use this js code: $('#target').actualizer('a'); On click at any A element,

Šimon (Simon) Rataj 1 Jul 28, 2020
jQuery quick notification plugin. jQuery плагин быстрых уведомлений

Note: English translation by Google Translate Notific About Description: this is a jQuery plugin that helps you display notifications on your site. Li

Webarion 2 Nov 7, 2021
jquery-input-mask-phone-number.js - A simple, easy jquery format phone number mask library

jquery-input-mask-phone-number A jQuery Plugin to make masks on input field to US phone format. Quick start 1. Add latest jQuery and jquery-input-mask

Raja Rama Mohan Thavalam 12 Aug 25, 2022
Create beautiful CSS3 powered animations in no time.

Bounce.js Bounce.js is a tool and JS library for generating beautiful CSS3 powered keyframe animations. The tool on bouncejs.com allows you to generat

Tictail 6.2k Dec 30, 2022
Composable data visualisation library for web with a data-first approach now powered by WebAssembly

What is Muze? Muze is a free data visualization library for creating exploratory data visualizations (like Tableau) in browser, using WebAssembly. It

Charts.com 1.2k Dec 29, 2022
The JavaScript and API powered WordPress.com

Calypso Calypso is the new WordPress.com front-end – a beautiful redesign of the WordPress dashboard using a single-page web application, powered by t

Automattic 12.2k Dec 30, 2022
⚪ SVG-Powered component to easily create skeleton loadings.

SVG-Powered component to easily create placeholder loadings (like Facebook's cards loading). Features ⚙️ Customizable: Feel free to change the colors,

Danilo Woznica 12.7k Jan 4, 2023
⚡️ lowdb is a small local JSON database powered by Lodash (supports Node, Electron and the browser)

Lowdb Small JSON database for Node, Electron and the browser. Powered by Lodash. ⚡ db.get('posts') .push({ id: 1, title: 'lowdb is awesome'}) .wri

null 18.9k Dec 30, 2022
📝 Minimalistic Vue-powered static site generator

VuePress 2 is coming! Please check out vuepress-next. Documentation Check out our docs at https://vuepress.vuejs.org/. Showcase Awesome VuePress vuepr

vuejs 21.1k Jan 4, 2023
The next small thing in web development, powered by Svelte

sapper The next small thing in web development, powered by Svelte. What is Sapper? Sapper is a framework for building high-performance universal web a

Svelte 7.1k Jan 2, 2023