How to display and animate image on scroll using JavaScript?

March 11, 2021

This is what we want.

How to display and animate image on scroll using JavaScript?

Whenever we want to change style or play with the HTML elements (add elements, animate elements) on scroll, the scrollTop property comes handy. We can scroll the content inside a div or the whole body using scrollTop property.

We are going to use the same scrollTop property to do the same. We are also going to use CSS to animate the image.


Which will just add basic HTML elements with some texts and an image like this:


Let’s style the texts a bit with Google fonts so it looks nice. Also, let’s hide the image initially with CSS visibility:hidden property. You can style the image as per your requirements.

We have added the animation in CSS for which we will add the @keyframes at the end.

Now, let’s add this CSS class which will be used to display the image on scroll.

Finally, the JavaScript

We are going to create a function and call it on a window.onscroll event. Let’s look at the function first.

In the function above, we are checking the distance from top using scrollTop. We don’t have much content so we are just checking if it’s greater than 100px. You can adjust it using your requirements.

We are check both the document.body(for Safari) and document.documentElement(for other browsers). If the condition matches then we’ll simply add the class we created in CSS.

This will do the trick. Well, mostly. We still need to add animation.

Let’s add the @keyframes for the animation we added earlier.

The animation makes the display of image really smooth.


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to uninstall Cocoapods from the Mac OS? #4 How to Use SQL MAX() Function with Dates? #5 How to add Read More Read Less Button using JavaScript? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Apr 7 Solution for “Yarn build: Failed because of a stylelint error” Apr 7 Make sure your links have descriptive text Apr 7 How to add Laravel to WordPress using Sage theme (and install Tailwind CSS)? Apr 2 How to create a sidebar using pure CSS? Apr 1 How to switch dark and light themes using pure CSS? Apr 1 How to calculate elapsed time in JavaScript?

You might also like these

Aggregate Functions Examples in Postgres for BeginnersPostgresWhat is Prototypal Inheritance in JavaScript?JavaScriptOpen Source Security Tools for Defense SecurityMiscFive common features of Angular template syntax (with examples)AngularThe order Property in Flex Items in CSSCSSHow to make HTML form interactive and using CSS?CSS