An Introduction to jQuery Scroll-based Animations

Share this article

Key Takeaways

  • Scroll-based animations and effects are a technique that allows web developers to create dynamic and interactive web experiences. They are triggered when a user scrolls down a page and can be manipulated and implemented with CSS and jQuery.
  • To create responsive scroll-based effects, it’s crucial to define the browser window’s width and height properties. Without these properties, the effects will not work correctly when the user resizes the window.
  • The tutorial provides four examples of scroll-based animations and effects, demonstrating how they change based on the values of the window’s width property. These examples include animating the opacity, height, width, left, right, and bottom properties of various elements.
  • The tutorial also includes a Frequently Asked Questions section, providing solutions to common issues such as creating a smooth scrolling effect, detecting scroll direction, and stopping a jQuery animation.

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.

Frequently Asked Questions (FAQs) about jQuery Scroll-Based Animations

How can I create a smooth scrolling effect using jQuery?

Creating a smooth scrolling effect using jQuery involves manipulating the scrollTop property. This property sets or returns the vertical scrollbar position for the selected elements. Here’s a simple example of how you can achieve this:

$('a').click(function(){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});
In this code, when a link is clicked, the page will smoothly scroll to the linked element over a period of 500 milliseconds.

Why is my jQuery onScroll event not firing?

If your jQuery onScroll event is not firing, it could be due to several reasons. One common issue is that the scroll event is attached to an element that doesn’t have a scrollbar. Ensure that the element you’re attaching the scroll event to is scrollable. Another issue could be a conflict with other scripts or libraries. Try disabling other scripts to see if the issue persists.

How can I scroll to a specific element using jQuery?

To scroll to a specific element using jQuery, you can use the animate() method in combination with the scrollTop property and the offset() method. Here’s an example:

$('button').click(function(){
$('html, body').animate({
scrollTop: $('#myElement').offset().top
}, 500);
});
In this code, when a button is clicked, the page will scroll to the element with the ID ‘myElement’ over a period of 500 milliseconds.

How can I detect the scroll direction using jQuery?

Detecting the scroll direction involves comparing the current scroll position with the previous one. Here’s a simple example:

var lastScrollTop = 0;
$(window).scroll(function(){
var currentScrollTop = $(this).scrollTop();
if (currentScrollTop > lastScrollTop){
console.log('scrolling down');
} else if (currentScrollTop < lastScrollTop){
console.log('scrolling up');
}
lastScrollTop = currentScrollTop;
});
In this code, the direction of the scroll is logged to the console each time the user scrolls.

How can I stop a jQuery animation?

To stop a jQuery animation, you can use the stop() method. This method stops the currently running animation on the selected elements. Here’s an example:

$('button').click(function(){
$('html, body').stop();
});
In this code, when a button is clicked, any running animation on the page will be stopped.

George MartsoukosGeorge Martsoukos
View Author

George is a freelance web developer and an enthusiast writer for some of the largest web development magazines in the world (SitePoint, Tuts+). He loves anything related to the Web and he is addicted to learning new technologies every day.

jQueryLouisL
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week