Tips for triggering animation only when the element is in the viewport

I'm currently developing in React and facing a challenge where I need to trigger a fade animation for an element only when it becomes visible on the screen. The issue is that right now, the animation plays as soon as the page loads, which defeats the purpose if the user has to scroll to see it.

<Grid container className="AnimationContainer">
  <img src="/images/animation1/circle.svg" className="Animation1-1" />
  <img src="/images/animation1/calculator.svg" className="Animation1-2" />
</Grid>

In my CSS file, I've defined the styles:

.AnimationContainer {
  place-content: center;
  height: 200px;
  width: 100%;
}
.Animation1-1 {
  animation: fading 2s;
}
.Animation1-2 {
  animation: fading 1.2s;
}
@keyframes fading{
  0%{opacity:0}
  100%{opacity:1}
}

Is there a way for me to ensure that the animation is triggered only when the Grid with class "AnimationContainer" or the images with classes "Animation1-1"/"Animation1-2" are within the visible portion of the screen?

Answer №1

Implement the Intersection Observer API to identify when the element becomes visible and apply the animation property at that point. Achieving this functionality is straightforward with the help of react-intersection-observer:

import { useInView } from "react-intersection-observer"

const CustomComponent => () => {
  const [ref, inView] = useInView({ threshold: 0.5 })

  return (
    <div ref={ref} className="AnimationContainer">
      <img src="/images/animation1/circle.svg" className={inView ? "Animation1-1" : null} />
      <img src="/images/animation1/calculator.svg" className={inView ? "Animation1-2" : null} />
    </div>
  )
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Activate and deactivate animation using one button with jQuery

Looking for a solution using Jquery. Can you animate an element when clicking a button and then stop the animation with the same button? Here is an example code snippet in JavaScript: $('<div>').css({ 'width':'200 ...

The Link tag in the Hero.jsx file of Next.js is malfunctioning and failing to redirect to the intended URL

Having a problem with the button in my Hero.jsx component, part of the Page.js implementation. The button uses a Link tag to redirect to the url.js page, but it's not working as expected and showing an Error 404 page instead. I'm new to Next.js s ...

Issue with Redux-form's type prop not functioning as expected with checkbox and radio components

Hey there, I'm new to working with redux forms and I've been trying to figure out how to use input types other than "text". I've read through the documentation but for some reason, types like "checkbox" or "radio" are not showing up in the b ...

Issue with resetting the state of a react-select component remains unresolved

I'm currently facing two issues with my react-select component: Firstly, once I select an option, I am unable to change it afterwards. Second, when my form is reset, the react-select component does not reset along with the other fields. For simplici ...

Creating objects that are a fraction of another's width

My goal is to create 3 responsive divs that fill the width of the window and adjust their width based on the window dimensions. However, I'm facing an issue with JavaScript where it seems to be miscalculating the window width, causing the objects to o ...

Encountering an ETIMEDOUT error while sending out large (10k) post requests with axios.all in a Node

I have implemented axios.all to make simultaneous post calls. Below is the code snippet: let postUrls = []; data.forEach(item => { const itemData = { stream: stream_name, key: item.serialNumber, addr ...

The div containers are unable to be positioned side by side

Hey there, I'm having trouble with my coding right now. (I'm not sure if you can see it, but the code is creating a div - frustrating). Here's an image of the code: No matter what code I try to use to align the content center, left, or righ ...

Why does it seem like only one div is being added?

I am facing an issue with dynamically appending multiple div elements. Despite my efforts, only one div element is showing up on the browser when I try to test the code. I have searched for similar problems but could not find any solutions. Any assistanc ...

Transforming JSON data into an HTML template

Incorporating Angular 6 in my project, I have come up with the following templates: Header, Left panel, Body part, Footer Header, Left panel, Body part, Right panel, Footer Header, Body part, Footer Considering the numerous templates, I am aiming to tran ...

Adapting Classes in Javascript Based on Screen Width: A Step-by-Step Guide

I'm dealing with two separate menus - one for mobile version and one for PC version. However, the mobile menu seems to be overlapping/blocking the PC menu. How can I resolve this issue? I've attempted various solutions such as removing the mobil ...

Withdrawal of answer from AJAX request

Is there a way to create a function that specifically removes the response from an AJAX call that is added to the inner HTML of an ID? function remove_chat_response(name){ var name = name; $.ajax({ type: 'post', url: 'removechat.php ...

Check to see if an array contains any falsy values and return accordingly

My goal is to only return the error message if any value is falsy, and never return the hooray message. I am utilizing lodash. var jawn = [ { "cheese" : true, "with" : true, "without" : true }, { "cheese" ...

What is the reason behind having to refresh my ReactJS page despite it being built with ReactJS?

I have developed a task management application where users can input notes that should automatically update the list below. However, I am facing an issue where the main home page does not display the updated todos from the database unless I manually refres ...

Get the data from the files in the request using request.files in Node.js

Is there a way to read the content of a file (either a txt or CSV file) that a user uploads without saving it to local storage? I know I can save the file in an upload directory and then read it from storage. However, I'm wondering if there is a way ...

Text that is superimposed onto an image

Struggling to implement a hovering text over an image? I attempted to follow a tutorial, but couldn't adapt it to my project. While I managed to create a fixed overlay, I aim for a responsive solution that adjusts with resolution changes. My goal is t ...

What could be causing issues with my ReactiveUserControl or ReactUI application when it comes to running Selenium auto tests with WinAppDriver using a C# test solution?

In my development experience, I have worked on creating a robust Automated Test solution using C#, WinAppDriver (also known as WAD), and Selenium. This solution was designed to test a complex WPF windows application. Things were going smoothly until the S ...

Ways to eliminate the default margin surrounding an image within a div

Struggling with CSS while building websites is a common issue for me. In my current project, I have encountered a challenge where I placed two images inside a div container. Oddly enough, when I add text to the div, it adjusts its height accordingly. How ...

Javascript: Harnessing Textbox Arrays for Improved Functionality

Check out the form displayed below. <form id="upload_form" enctype="multipart/form-data" method="post"> <input type="text" name="name[]" id="name"><br> <input type="text" name="name[]" id="name"><br> <input type="fil ...

Exploring the intricacies of managing nested data in a Firebase Database (web)

I understand this question may have similarities to others already asked, so my apologies in advance. I am seeking a clear, up-to-date solution that aligns with my expectations. If I have an object labeled "Item One", how can I retrieve the array of "subI ...

In React, transfer the status of various types of pressed buttons and send already pressed buttons to another component

My component consists of multiple buttons arranged in different types and subtypes. The goal is to save the state of each clicked button using a hook containing an array of objects representing the click state of each subtype. Additionally, there is a < ...