Third & GroveThird & Grove
Feb 17, 2017 - Matt Brooke

Super Simple Parallax Effect with jQuery or Native JS

For those familiar with the web design world, a persistently desired design feature for the past few years is “parallax” scrolling. Now, the word parallax is basically meaningless in and of itself. It could refer to something as simple as a fixed background, to something as complex as a video scrubbing based on your scroll inputs. However, what most people mean when they say “parallax” is an element that scrolls at a slightly different speed than the rest of the page, giving the sense that it lies “behind” the rest of the content. This can be accomplished in a number of ways. There are a bevy of jQuery plugins available to do this, and it has started to be adopted into frameworks like Materialize. However, if you’re rolling your own JS and CSS, there is no reason to add yet another HTTP request to your page for an effect that can be easily accomplished in 5 lines of code, as such:

 

$(window).scroll(function() {
        var scrollTop = $(window).scrollTop();
        var imgPos = scrollTop / 2 + 'px';
        $('.hero').find('img').css('transform', 'translateY(' + imgPos + ')');
    });

 

It really is that simple. We simply grab the distance from the viewport to the top of the page on scroll, divide it by 2 and apply a transform property with that value to your desired element. You could easily build this out into a reusable function like so:

 

function simpleParallax(intensity, element) {
        $(window).scroll(function() {
            var scrollTop = $(window).scrollTop();
            var imgPos = scrollTop / intensity + 'px';
            element.css('transform', 'translateY(' + imgPos + ')');
        });
    }

 

Now we can easily instantiate this function on any element and adjust the differential of the scrolling speed with the “intensity” property. These examples assume you are using jQuery, but it’s quite easy to accomplish this with vanilla JS as well. Check out youmightnotneedjquery.com for vanilla alternatives to common jQuery tasks.