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 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

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 check if checkbox is checked or not using JavaScript?JavaScriptHow to remove WordPress TinyMCE Editor buttons?WordPressHow to add Local State to a Class in React?ReactSorting Object Arrays in JavaScriptJavaScriptHow to create a simple tab interaction using CSS?CSSThe difference between isFinite() method and isFinite() function in JavaScriptJavaScript