Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to understand various snippets of setTimeout() function in JavaScript ?
Next article icon

How to add fade-in effect using pure JavaScript ?

Last Updated : 30 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

The fade effect is described as the gradual increase and decrease in the opacity of the selected portion. In other words, the fade effect is termed as the increase and decrease in opacity with respect to time. When this effect is applied with a gradual increase in the opacity it is known as the fade-in effect. This is the effect that is used to apply fade-in on the selected part of the page with the selected interval of time. 

We are using the setInterval() method and clearInterval() method in these logics. 

Using setInterval() Method: On page loading, we are calling a function called the fadeIn() method. We are using the setInterval() method which takes two parameters one is function reference(which is the show() in this case) and the other is the timer(in number), which will call the show() function after every given time interval. 

In the show() function, we are taking the property opacity in the variable name 'opacity' and increasing it by 0.1 every time the fadeIn() function is called. Initially, the opacity of the selected portion is set to 0. Two variables opacity and intervalID are declared inside the script tag. Variable opacity deals with the opacity of the project, while intervalID is used to call clearInterval() function. 

Then window.onload=fadeIn, is used to call the fadeIn() function automatically. The fadeIn() function calls an in-built method setInterval(), which takes two parameters, one function reference(show() in this case), and a time interval(to take reference of function after the selected interval). In setInterval(), the show() function is called after every 200 milliseconds in which we are checking the opacity of the body(variable body holds complete body with the help of id), if it is less than 1 there will be an increment of 0.1 in opacity otherwise clearInterval() function is called which will stop the function calling for show(). 

Note: The opacity of the selected portion is set to zero to understand the effect.

Example: This example shows the above-explained approach.

JavaScript
<body id="body" style="opacity: 0;">     <br>     <h1 style="color: green">GeeksforGeeks</h1>     <b>         How to create fade-in effect         on page load using javascript     </b>     <p>         This page will fade-in after loading     </p>      <script type="text/javascript">         var opacity = 0;         var intervalID = 0;         window.onload = fadeIn;                  function fadeIn() {             setInterval(show, 200);         }                  function show() {             var body = document.getElementById("body");             opacity = Number(window.getComputedStyle(body)                             .getPropertyValue("opacity"));             if (opacity < 1) {                 opacity = opacity + 0.1;                 body.style.opacity = opacity             } else {                 clearInterval(intervalID);             }         }     </script> </body> 

Output:

Using clearInterval() method: In this approach, complete logic is written inside a variable which is done with the help of the setInterval() method, here complete function is to be written in place of function reference. This approach is comparatively easy to understand. The default value of opacity is 1. So we have to set it to zero. to observe the output The window.onload=fadeIn is used to call the fadeIn() function automatically. Now declaring 3 variables in fadeIn() function:

  • fade: It is to fetch the part on which the fade-in effect is to be applied.
  • opacity: It is to deal with the opacity of fetched portion.
  • intervalID: It is to deal with complete logic and terminate logic.

Now instead of writing a function reference, a complete function is to be written, which will be called over and over again after every 200 milliseconds to increase opacity. Now in the written function, the opacity of the fetched portion is compared with 1 on each call

  • If opacity is found less than 1, the opacity will increase by 0.1 and be applied to the fetched portion.
  • If opacity is found 1 or greater than 1, clearInterval() function is called to terminate function calls.

Example: This example shows the above-explained approach.

JavaScript
<body id="body" style="opacity:0;">     <br>     <h1 style="color: green">GeeksforGeeks</h1>     <b>         How to create fade-in effect         on page load using javascript     </b>     <p>         This page will fade-in after loading     </p>      <script type="text/javascript">         window.onload = fadeIn;                  function fadeIn() {             var fade = document.getElementById("body");             var opacity = 0;             var intervalID = setInterval(function() {                          if (opacity < 1) {                     opacity = opacity + 0.1                     fade.style.opacity = opacity;                 } else {                     clearInterval(intervalID);                 }             }, 200);         }     </script> </body> 

Output: This output video is in the loop, which is why it is not stopping after getting opacity 1. It loads again and again automatically. 

Note: If the increment value is greater than 0.1, it fade-in faster. If the time interval decreases then also it fade-in faster.


Next Article
How to understand various snippets of setTimeout() function in JavaScript ?
author
_mridul_bhardwaj_
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions

Similar Reads

  • How to override a JavaScript function ?
    In this article, we are given an HTML document and the task is to override the function, either a predefined function or a user-defined function using JavaScript. Approach: When we run the script then Fun() function is called. After clicking the button the GFG_Fun() function is called and this funct
    2 min read
  • Using the function* Declaration in JavaScript
    The function* declaration is used to define a generator that returns a Generator object. Generators are very powerful for asynchronous programming as they aim to resolve callback problems. In a generator, the yield keyword is used instead of return. The yield statement suspends the function’s execut
    2 min read
  • What is the difference between call and apply in JavaScript ?
    JavaScript call() Method: It calls the method, taking the owner object as an argument. The keyword this refers to the 'owner' of the function or the object it belongs to. We can call a method that can be used on different objects. Syntax: object.objectMethod.call( objectInstance, arguments ) JavaScr
    2 min read
  • How to find out the caller function in JavaScript?
    In this article, we see the methods to find out the caller function in Javascript. Sometimes, the developer may want to modify how a function works on the basis of its caller function. To find out the caller function name, we will use the Function object's caller property. Property: Function.caller
    1 min read
  • How to negate a predicate function in JavaScript ?
    In this article, we will see how to negate a predicate function in JavaScript. Predicate functions are the ones that check the condition and return true and false based on the argument. Our task is to get the opposite of the predicate function. We follow the following method to get the desired resul
    3 min read
  • How to iterate over a callback n times in JavaScript?
    Given a callback function, we have to iterate over a callback n times. The callback is a function that is passed as an argument. To iterate over the callback function, we have to run the callback function n time. Here we have some common approaches: Table of Content Using recursion to iterate the n
    4 min read
  • How to call function from it name stored in a string using JavaScript ?
    In this article, we will call a function from the string stored in a variable. There are two methods to call a function from a string stored in a variable. Using window object methodUsing eval() method Note: The eval() method is older and is deprecated. Method 1: Using the window object. The window
    2 min read
  • How to measure time taken by a function to execute using JavaScript ?
    This article will show how to measure the time taken by a function to execute using Javascript. To measure the time taken by a function to execute we have three methods: Table of Content Using the Using Date ObjectUsing the performance.now() methodUsing the console.time() methodMethod 1: Using the U
    3 min read
  • How to check a function is defined in JavaScript ?
    In this article, we will check whether a function is defined or not in JavaScript. The JavaScript typeof operator is used to check whether the function is defined or not. JavaScript typeof OperatorThe typeof operator is used to find the type of a JavaScript variable. This operator returns the type o
    2 min read
  • How to wait for a promise to finish before returning the variable of a function ?
    Waiting for a promise to finish before returning a variable in a function is crucial when dealing with asynchronous operations in JavaScript, like fetching data from an API. Using async and await allows the function to pause execution until the promise resolves, ensuring reliable and expected result
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences