Coder Social home page Coder Social logo

plax's Introduction

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.

plax's People

Contributors

acetous avatar borntodesign avatar bryant1410 avatar cameron423698 avatar cameronmcefee avatar craigblagg avatar danferth avatar ded avatar dzuelke avatar holman avatar jaripekkala avatar josh avatar kkirsche avatar lukekarrys avatar magebarf avatar pastjean avatar robloach avatar tjschuck avatar valeriansaliou avatar yury avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

plax's Issues

Ender/Jeesh support is broken

As mentioned in my previous pull requests, I did notice that Ender (Jeesh) support is currently broken.

I've noticed a few places where things are not working as intended, and I thought I'd outline them here;

  • Jeesh (Bonzo) does not have a position method. This is currently being used to initialize the starting positions for each layer. One could calculate the same by using the offsetLeft and offsetTop, but as this does not take margin parameters into considerations (unlike jQuery's .position()) it would have to be retrieved and parsed from the css attributes. Currently, the single line var position = layer.obj.position() would be replaced with the following block;
        var marginLeft = layer.obj.css('margin-left') || '0px'
        var marginTop = layer.obj.css('margin-top') || '0px'

        marginLeft = marginLeft.match(/^((-?\d+)\s*px|0+\s*%|left)$/)
        marginTop = marginTop.match(/^((-?\d+)\s*px|0+\s*%|top)$/)

        marginLeft = marginLeft ? parseFloat(marginLeft[2]) : 0
        marginTop = marginTop ? parseFloat(marginTop[2]) : 0

        // Figure out where the element is positioned, then reposition it from the top/left
        var position = { left : this.offsetLeft - marginLeft, top : this.offsetTop - marginTop }
  • Jeesh does not handle calling .width() on the window or document objects properly. This makes all the examples where the activity target is not set to an explicit element throw errors (at least running chrome). A workaround would simply be setting the activity target to the body element, but that would give a very small area and odd behavior if one tries to apply it to the examples.
  • Jeesh's (Bonzo's) offset() has the same issue as listed above, it does not take margin into consideration, at least not when it is set explicitly. This makes the specific element example, where the parallax box has a top margin of 100px and a left margin of auto, act very weird. The parallax effect is triggered whenever moving your mouse pointer above the box, down to 100px from the bottom of it, where the effect stops.

All in all, the issues with running Plax with Ender / Jeesh / Bonzo instead of jQuery could be fixed, but I believe that there at least needs to be a few fixes incorporated in Bonzo and the Ender Bridge before it would be worth the time.

My suggestion is to currently remove Ender from the documentation, only promising compatibility with jQuery, while I open up some issues with the Bonzo project instead, and then consider adding it back in the future.

3gs support

Plax does not support 3gs due to the fact it does not have a gyroscope but only an acceletometer

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.

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

Invert: Bad parameter.

It would seem that the invert property is helpful and convenient. It's not.

It's not needed, and limits what the user thinks can be done with Plax.

Not needed

I say it's not needed, because the same effect can be achieved with a little less code.

Instead of..

$('#id').plaxify({ 'xRange': 50, 'yRange': 50, invert: true });

..you could just do..

$('#id').plaxify({ 'xRange': -50, 'yRange': -50 });

Limits what the user thinks can be done

Now what could I possibly mean by this?

It makes the user feel like inversion is all or nothing.

You can actually invert just one axis. This wouldn't be true parallaxing, but if the user just wants to use the plugin to move stuff around, then why not let them?

Say you want only x to be disobedient..

 $('#id').plaxify({ 'xRange': -50, 'yRange': 50 });

..then that would do the trick for you.

Cleaner code

I also noticed that you use a lot of if (invert) statements, that could be avoided if you removed the parameter.

It would break the API for a few people, and a few of your use cases, but I think it overall improves usability.

Effect stops after a few seconds

When using in Firefox Nightly 17.0a1, the effect stops after a few seconds apparently for no reason.
It does work in the latest stable Firefox though.

Plain JS version?

Any chance supporting a vanilla JavaScript version is on the roadmap?

chrome and safari performance issue

Hi,

I'm trying to use plax (4 image, sizes 1778x720 png) but only chrome and safari cant handle plax effect. its very slow. is it coused by plugin or spesific browser issue? ie and ff has no problem. very fast and smooth

thank you

Calculate position based on % rather than px

I am trying to incorporate this into a responsive design, but as soon as the width changes, it breaks (or rather, the px position doesn't change based on it's parent.

Is there a way to calculate position based on % instead of px?

example (live for now). http://beta.cibgraphics.com (change the width of the browser to achieve a different container width and you will see elements are hidden or have too much space depending on how you resize the browser)

enable/disable plax few times ipad/iphone stop working

I have 6 diffrent div, every div has 4 png. this divs in a slider. when slider init I'm enabling plax on number 1 div. when I slide to another div disable number 1 div and activate second div's plax. its working fine. but in ipad or iphone after few times disable/enable parallax stop working.

here is sample two function when change slide. Am I doing wrong?

thank you

function initSlideOne() {
$.plax.disable({ "clearLayers": true, "restorePositions": true });
$("#SlideOne img.layer1").plaxify({ "xRange": 0 });
$("#SlideOne img.layer2").plaxify({ "xRange": 100 });
$("#SlideOne img.layer3").plaxify({ "xRange": 130 });
$("#SlideOne img.layer4").plaxify({ "xRange": 100, "invert": true });
$("#SlideOne img.layer5").plaxify({ "xRange": 200, "invert": true });
$.plax.enable({ "activityTarget": $('#SlideOne') });
}

function initSlideTwo() {
$.plax.disable({ "clearLayers": true, "restorePositions": true });
$("#SlideTwo img.layer1").plaxify({ "xRange": 0 });
$("#SlideTwo img.layer2").plaxify({ "xRange": 100 });
$("#SlideTwo img.layer3").plaxify({ "xRange": 130 });
$("#SlideTwoe img.layer4").plaxify({ "xRange": 100, "invert": true });
$("#SlideTwo img.layer5").plaxify({ "xRange": 200, "invert": true });
$.plax.enable({ "activityTarget": $('#SlideTwo') });
}

Calculation errors in Webkit with CSS3 features

I've noticed miscalculations in webkit-based browsers when using CSS3 features like Transition and Transform:

{webkit-transition: .2s all ease-in}
{webkit-transform:scale(0.65)}

Video example: http://screencast.com/t/6ZdlGaC4obt

It stumped me for a little while, but as I was withering on about in previous thread, I think it's something to do with line 78 in plax.js.

Sorry for the previous confusion.

Using plax multiple times on a page

So I have set up two zones #one & #two to use plax in. It seems that plax #one has control of both zones.

Here is my setup, am I doing anything wrong?

//PLAX - ONE
$('#one img').plaxify()
$('#one  .back').plaxify({ "xRange": 50, "yRange": 0 })
$('#one .front').plaxify({ "xRange": 30, "yRange": 0, "invert": true })
$.plax.enable({ "activityTarget": $('#one') })

//PLAX - TWO
$('#two img').plaxify()
$('#two .back').plaxify({ "xRange": 50, "yRange": 0, "invert": true })
$('#two .front').plaxify({ "xRange": 30, "yRange": 0 })
$.plax.enable({ "activityTarget": $('#two') })

Cheers Sean.

Sluggish on Firefox

Is anybody else having this issue? Plax works perfect on Chrome, Safari, even IE9 works fine. To be more specific, it just sluggish hard on Firefox for Mac. On Windows lets says its acceptable.

Responsive

First let me preface that I am VERY much a newbie here and to java script as well.
Although I love the script and its functionality. It doesn't seem to be responsive. If you size the window down narrower than the all of the elements they are off canvas.

So far the only way I can get it to somewhat work is by doing a reload.
window.addEventListener('resize', function () { "use strict"; window.location.reload(); });

This is a very archaic way of doing so.
Are there any other ways of accomplishing the re-positioning of the elements based on the window size?

Add left/right X & up/down Y ranges

Hi, it would be great if we'll can specify for example:
<img src="..." data-lxrange="200" data-rxrange="50" data-uyrange="50" data-dyrange="0">

$.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') }
);

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.

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!

ActivityTarget

The current activity target only captures the window. If you scroll down a little on a page, the new area won't be accounted for.

Changing the default plaxActivityTarget to $(document) will help with this.

Not quite sure if this is a bug, or an intentional. Took me a while to figure out :P

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.

error using plax with bonzo via ender

there seems to be a conflict with plax and bonzo:

when running with the following ender build

ender-js backbone qwery bonzo bean domready bowser ender-bootstrap ender-json browser-request morpheus plax

on page load i get:

TypeError: 'undefined' is not an object (evaluating 'el.style.position')

seems to raise a conflict within bonzo's dim function (line #8 below):

 , dim: function () {
          if (!this.length) return { height: 0, width: 0 }
          var el = this[0]
            , orig = !el.offsetWidth && !el.offsetHeight ?
               // el isn't visible, can't be measured properly, so fix that
               function (t, s) {
                  s = {
                      position: el.style.position || ''
                    , visibility: el.style.visibility || ''
                    , display: el.style.display || ''
                  }
                  t.first().css({
                      position: 'absolute'
                    , visibility: 'hidden'
                    , display: 'block'
                  })
                  return s
                }(this) : null
            , width = el.offsetWidth
            , height = el.offsetHeight

          orig && this.first().css(orig)
          return {
              height: height
            , width: width
          }
        }

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).

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);

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 );

adds left margin to margin-left

I use margin to position my absolute elements, I've found it to be better in many scenarios than using left:0; top:0; etc...

When using plax, in Chrome and Safari (not FF) plax adds the 'left: 362px' where i have margin-left: 362px , therefore making it positioned too far left by 362px (its total margin is now 724px).

This is really annoying.

Effect stop working when mouseover an iframe

Hello,
First of all, thank´s so much for this awesome plugin.
I have a web with some iframes, and when the cursor goes over the oframe area, the plax effect on the layers behind stop working, I´have tried something like this $.plax.enable({ "activityTarget": $('#viewport, .frames')}) to target also the container of the layer to be "plaxed" and the ifrmaes, but it doesn´t worked,
altough y tried $.plax.enable({ "activityTarget": $('.frames')}) just to see if it´ll work at least on the iframes, but it didn´t.
Is there a way to achieve that??
Thanks

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

High CPU-load while moving the mouse

While moving your mouse, plax can generate a high cpu-load. Having 3 or more moving elements at the same time can consume up to 40% CPU-load on my Q6600 using Chrome.
Maybe a maximum of rendered fps would limit the CPU-usage instead of reacting to every mousemove event.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.