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.

HTML

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

CSS

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 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #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
You might also like these
How to remove special characters (dash, asterisk etc) from any string in PHP?PHPWhat is the difference between float and double?MiscellaneousWhat’s the difference between a Framework and a Library?MiscellaneousDoes :is() pseudo selector hint at CSS preprocessing in the future?CSSHow to display a student’s individual transcript in Colleague?ColleagueLearn how to give a temporary name to a column or to a table using SQL AliasesSQL/MySQL