An Introduction to jQuery Scroll-based Animations

George Martsoukos
Tweet

The web changes every day. New technologies and techniques emerge and others disappear. For this reason, web designers and front-end developers have to be familiar with many of the latest web design trends. Parallax scrolling, fixed headers, flat design, one-page websites, and animations are some of the hottest current web trends.

In this tutorial, we’ll take a look at scroll-based animations and effects using CSS and jQuery.

The four effects that we’ll be creating can be viewed in this demo. But before we get to the effects, let’s have a brief intro.

Note: The code used in this tutorial could be improved with object caching and the use of CSS animations instead of jQuery’s `animate()` method, but for simplicity, we’ve repeated object declarations and we’ve kept everything inside jQuery to keep things focused on the concepts.

What are Scroll-based Animations and Effects?

Scroll-based animations and effects are a new, yet well-known technique that gives front-end developers the ability to create rich and interactive web experiences. They’re fired when a user scrolls down a page and they can be easily manipulated and implemented with CSS and jQuery.

In order to detect whether a user is scrolling down the page, we use jQuery’s scroll() event.

Once we know that the user is scrolling, we can get the vertical position of the window’s scrollbar using jQuery’s scrollTop() method and apply the desired effects:

$(window).scroll(function() {
    if ($(this).scrollTop() > 0) {
        // apply effects and animations
    }
});

Are They Responsive?

If we’re interested in creating responsive scroll-based effects, we have to define the following properties:

  1. The browser window’s width property.
  2. The browser window’s height property.

Without these properties defined, we create scroll-based effects that are “static” and will not work correctly when the user resizes the window’s either horizontally or vertically.

We can easily retrieve the values of these properties using jQuery’s width() and height() methods.

The following code snippet shows all the necessary checks that we have to take into account in order to create scroll-based effects.

$(window).scroll(function() {
    if ($(this).width() < 992) {
        if ($(this).height() <= 768) {
            if ($(this).scrollTop() < 500) {
                // apply effects
            }
            if($(this).scrollTop() > 1000) {
            // apply effects
            }
        }
    }
});

Now that we have covered the basics for scroll-based effects, let’s see them in action through four different examples.

Note: For simplicity reasons, we’re only focusing on checking how these effects change based on the different values of the window’s width property. The same process could also be used for its height property.

Example #1

This effect is triggered when the top position of the window’s scrollbar exceeds 60px. In such a case, the code snippet that is executed is the following:

if ($(window).scrollTop() > 60) {
    $('.banner h2').css('display', 'none');
    $('.banner .info').css('display', 'block');
} else {
    $('.banner h2').css('display', 'block');
    $('.banner .info').css('display', 'none');
}

The code above hides the h2 child element of the .banner element and shows its .info child element, which was initially hidden.

This code could also have been written as follows:

if ($(window).scrollTop() > 60) {
    $('.banner h2').hide();
    $('.banner .info').show();
} else {
    $('.banner h2').show();
    $('.banner .info').hide();                               
}

To see the effect in action, view the full demo on CodePen.

Example #2

This next effect depends not only on the top position of the browser’s scroll bar, but also on the width of the window’s. More specifically, we are making the following assumptions:

  1. The window’s width property has a value less than or equal to 549px. In such a case, the animation is triggered only when the top position of the window’s scrollbar exceeds 600px.
  2. The window’s width property has a value between 550px and 991px. In such a case, the animation is triggered only when the top position of the window’s scrollbar exceeds 480px.
  3. The browser’s width property has a value greater than 991px. In such a case, the animation is triggered only when the top position of the window’s scrollbar exceeds the 450px.

The aforementioned assumptions result in the following code snippet:

if ($(window).width() <= 549) {
    if($(window).scrollTop() > 600) {
        // the animation that's executed
        firstAnimation();
    }
} else if ($(window).width() > 549 && $(window).width() <= 991) {
    if($(window).scrollTop() > 480){
        // the animation that's executed
        firstAnimation();
    }
} else {
    if ($(window).scrollTop() > 450) {
        // the animation that should be executed
        firstAnimation();
    }
}

The code that contains the animation to be executed is the following:

var firstAnimation = function () {
    $('.clients .clients-info').each(
        function () {
            $(this).delay(500).animate({
                opacity: 1,
                height: '180',
                width: '250'
            }, 2000);
        }
    );
};

The code above animates the opacity, height and width properties of the .clients-info elements.

To see this effect in action, view the full demo on CodePen.

Example #3

The third effect depends not only on the top position of the window’s scrollbar, but also on the width property of the window. More specifically, we are making the following assumptions:

  1. The window’s width property has a value less than or equal to 549px. In such a case, the animation is triggered only when the top position of the window’s scrollbar exceeds 1750px.
  2. The window’s width property has a value between 550px and 991px. In such a case, the animation is triggered only when the top position of the window’s scrollbar exceeds 1150px.
  3. The window’s width property has a value greater than 991px. In such a case, the animation is triggered only when the top position of the window’s scrollbar exceeds 850px.

And here’s the code based on the above:

if ($(window).width() <= 549){
    if($(window).scrollTop() > 1750){
        secondAnimation();
    }
} else if ($(window).width() > 549 && $(window).width() <= 991) {
    if ($(window).scrollTop() > 1150) {
        secondAnimation();
    }  
} else {
    if ($(window).scrollTop() > 850) {
        secondAnimation();
    }
}

The code that contains the animation to be executed is the following:

var secondAnimation = function() {          
    $('.method:eq(0)').delay(1000).animate({
				opacity: 1
			}, 'slow', 
			function() {
				$(this).find('h4').css('background-color', '#b5c3d5');
        }
    );

    $('.method:eq(1)').delay(2000).animate({
				opacity: 1
			}, 'slow', 
		    function() {
    	        $(this).find('h4').css('background-color', '#b5c3d5');
        }
    );

    $('.method:eq(2)').delay(3000).animate({
				opacity: 1
			}, 'slow', 
		    function() {
    	        $(this).find('h4').css('background-color', '#b5c3d5');
        }
    );

    $('.method:eq(3)').delay(4000).animate({
				opacity: 1
			}, 'slow', 
	        function() {
    	        $(this).find('h4').css('background-color', '#b5c3d5');
        }
    );
};

The code above sequentially animates the opacity property of the .method elements and then changes the background-color property of their h4 child elements.

To see the effect in action, view the full demo on CodePen.

Example #4

This effect depends not only on the top position of the window’s scrollbar, but also on the window’s width property. More specifically:

  1. If the window’s width property has a value less than or equal to 549px, the animation is triggered only when the top position of the window’s scrollbar exceeds 3500px.
  2. If the window’s width property has a value between 550px and 991px, the animation is triggered only when the top position of the window’s scrollbar exceeds 2200px.
  3. If the window’s width property has a value greater than 991px, the animation is triggered only when the top position of the window’s scrollbar exceeds 1600px.

This results in the following code:

if ($(window).width() <= 549) {
    if ($(window).scrollTop() > 3500) {
        thirdAnimation();
    }
} else if ($(window).width() > 549 && $(window).width() <= 991) {
    if ($(window).scrollTop() > 2200) {
        thirdAnimation();
    }
} else {
    if ($(window).scrollTop() > 1600) {
        thirdAnimation();
    }
}

The code for the animation is the following:

var thirdAnimation = function() {
    $('.blogs').find('p').delay(1400).animate({
            opacity: 1, 
            left: 0
        }, 'slow'
    );

    $('.blogs').find('img').delay(2000).animate({
            opacity: 1, 
            right: 0
        }, 'slow'
    );

    $('.blogs').find('button').delay(2500).animate({
            opacity: 1, 
            bottom: 0
        }, 'slow'
    );
};

The code above sequentially animates the opacity, left, right and bottom properties of the p, img, button elements.

To see the effect in action, view the full demo on CodePen.

Conclusion

I hope the four examples here demonstrate how you can use jQuery to create scroll-based animations and effects.

If you have any thoughts on the code used or know of any good advanced examples or demos of such effects, feel free to share them in the comments.

Free JavaScript: Novice to Ninja Sample

Get a free 32-page chapter of JavaScript: Novice to Ninja

  • George

    Hi, huphtur. This is a very nice and easy to use library! Thanks!

  • Vasi

    the main problem that i see with scroll based animations is that they do not work on mobile.
    i mean they do but is completely different then in browsers.

    especially you do not get and events while it accelerates or decelerates.

    are there any solutions to that?

  • M S

    Sorry but…

    Like 99.99% of all people building things like this, you forgot to test the page on a screen bigger than yours.

    Absolutely nothing happens when i scroll, until i make the window smaller.

    I use my screen in portrait mode, just so i wont need to scroll more that absolutely necessary.
    Ironically, because of this I see sites break and look like shit every day, where the designer apparently first has tried to spread out the page as much as possible to force scrolling, and then has added “cool effects” at scrolling.

    And next year (and beyond) when 4k-screens become dirt-cheap, these sites will blow up nicely on everyone elses screens too.

    This stupid fucking fad needs to die yesterday, sealed alive and screaming into the same tomb with low-contrast-design, and sooper-flat-design.

    Here is some basic common sense, boring-but-actually-works rules, for any of you kids out there who are considering building something using this awzomo kewlness:

    1.) If your content already fits on the screen, don’t hide it and force the visitor to scroll for it.
    2.) If some of your content doesn’t fit on the screen, its ALREADY hidden, and is already absolutely fabulously and magically revealed when the visitors scrolls. All with zero code.

  • http://www.forbenmedia.com/ Rick Yentzer

    Would like to know how difficult it would be to reproduce this in vanilla JS and CSS? Still in the process of learning JS.

    • http://georgemarts.com/ George Martsoukos

      Hi Rick. If you don’t want to use jQuery, you can try something like this:

      window.onscroll = function() {
      if (window.scrollY > 60) {
      console.log('scrolling');
      ...
      }
      };

      • http://www.forbenmedia.com/ Rick Yentzer

        Worked perfect. Thanks!