How to make Multi-Layered Parallax Illustration with CSS & Javascript
Patryk Zabielski
367
Parallax Code Suggestions
Thanks for the nice tutorial! Great artwork and effect. A few suggestions:
- When coding something intended for beginners, I’d recommend avoiding obfuscating preprocessors like CoffeeScript or Haml. Though the syntax is more concise, they can really hide what’s actually happening and make it more difficult to learn.
- Instead of two different attributes, one for selecting ( `data-parallax` ) and one for the actual value ( `data-depth` ), combine the two! A simple `data-parallax-depth` attribute will serve the purpose of selecting the layers and getting the value.
- The cross-browser `transform` styles you have in there aren’t quite correct. For Javascript, the CSS properties are camelCase instead of hyphenated ( `webkitTransform` instead of `-webkit-transform` ).
For better performance:
- Instead of setting the cross-browser styles on every element on every loop, you can also perform a simple check to see what the browser supported property is once on initialization and set only that property.
// Get vendor prefixed property for `transform`
var div = document.createElement(‘div’),
props = ‘transform webkitTransform mozTransform msTransform oTransform’.split(‘ ‘),
prop;
for (i = 0, len = props.length; i < len; i++){
if ( props[i] in div.style ) {
prop = props[i]; break;
}
}- Move your variable declarations and`querySelectorAll` call outside of the `scroll` event listener.
- Call `requestAnimationFrame` to run the layer loop so that the layers aren’t updated every scroll call, but only on frame rendering. Performance should be much smoother.
function updateLayers(){
topDistance = this.pageYOffset;
for (i = 0, len = layers.length; i < len; i++) {
layer = layers[i];
depth = layer.getAttribute(attr);
movement = -(topDistance * depth);
layer.style[prop] = 'translate3d(0, ' + movement + 'px, 0)';
}
frame = false;
}
window.addEventListener('scroll', function() {
frame = frame || requestAnimationFrame(updateLayers);
});I’ve updated your CodePen with those suggestions in mind: http://codepen.io/shshaw/pen/QNOjYP?editors=0010