Yogesh Chauhan's Blog

How to display and animate image on scroll using JavaScript?

in JavaScript on 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 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface #Jan 14 How to display a student’s individual transcript in Colleague? #Jan 11 How to install PuTTY on a MacOS?
You might also like these
What’s a repository on Github?MiscellaneousCurrencyPipe in Angular 9 with ExamplesAngularControl Scrolling with CSS Scroll SnapCSSWhat are partials in SCSS (Sass)?SCSSColleague UI Basics: Accessing the user interfaceColleagueDynamically generate names in SCSS (animation example)SCSS