Simple Optimized Parallax

Parallax – you love it or you hate it, but web designers will incorporate it into new designs regardless. This web design trend has been all the rage over the past few years, with countless javascript libraries existing to help make things a bit easier. However, it can be difficult to customize them to your liking, and sometimes you just want something a bit more lightweight.

In a recent project I ran into something that I hadn’t done before. The designs provided were very precise, but they also were going to be content managed. They wanted parallax on a bunch of the items on screen, but didn’t want the parallax to break their precise designs. With all of the javascript libraries I tried, parallax was calculated by how far you have scrolled down the page, with the transition distance based on that height. This is great and can look cool, but if you have a site of variable height due to being content managed, this wont work. If the page is modified to be shorter or longer than it was when you designed it, by the time you scroll to that parallax element it may be a lot higher or lower than you had intended it to be. I needed a better solution, so I made my own little parallax function for my project utilizing a little jQuery function called isOnScreen, which returns true if a given element has at least 1 pixel within the viewport.

Here’s what I came up with:

$(window).scroll(function(){
  $('.parallax').each(function(){ 
    if ($(this).isOnScreen()) {
      var firstTop = $(this).offset().top;
      var winScrollTop = $(window).scrollTop();
      var shiftDistance = (firstTop - winScrollTop)*0.2;
      $(this).css({"transform": "translate3d(0px, " + shiftDistance + "px, 0px)"});
    }
  });
});

First, I set everything up to run on window scroll. I have attached a parallax class to the element I want to be affected by the parallax effect. Then, I check to see whether or not the element is within the viewport. This means I can be more precise with my parallax effect because I know exactly when it is engaged. I then get the distance of the element to the top of the page, the distance of scroll from the top of the page, and then calculate a distance to shift the element based off of those two variables combined with a multiplier, which determines scroll speed. I then simply apply a translate3d with that shift distance to move the object. This allows us to only run parallax on that element while it’s on screen, optimizing resources for the page and keeping the animations clean. I use transform3d in this case (as opposed to transformY) to tell the browser to engage the graphics card, if possible, resulting in a buttery transition.

 

 

This was a pretty easy approach to parallax that I hadn’t used before, and hopefully will help make your next project go a bit smoother.

Happy coding!