YogeshChauhan . com

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.

amazon

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 add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

How to detect the Blog Page in WordPress?WordPressHow SCSS (Sass) finds a module without a file extension?SCSSForcing the domain to serve securely using HTTPSMiscHow to refresh a page using PHP at regularly occurring intervals?PHPthe box-sizing property in CSSCSSHow to change CSS with JavaScript?CSS