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

Implement a jQuery slider that pauses on hovering

Currently, I am grappling with the clearInterval function in a small jQuery project. To better illustrate the issue, I have created a jsFiddle example: http://jsfiddle.net/eWTSu/ While the rotation works smoothly, I encountered an obstacle when hovering ...

What is the best way to iterate through an ID using jQuery?

After pulling the list of doctors in my area from the database and displaying it on my webpage, I now want to load each doctor's "About" content inside a Bootstrap modal. I added an "about" column within the same database table where the doctors' ...

Customizing MaterialUI styles in React: A step-by-step guide

When utilizing Material UI with React, I am facing difficulty styling the Outline Select component according to my preferences. How can I override the default styles effectively? Even after using withStyles, I am unable to achieve the desired appearance a ...

Customizing table row background color on hover or mouseover in Material UI datatable

Completely new to React and Material-UI. I'm attempting to modify the color of table rows when hovering over them with the mouse. I have tried various solutions from different posts but none have worked for me. (e.g. Root, cell, and tableRow) The x ...

Is there a way to implement a watch on $validator.errors in Vue.js using the Vee Validation plugin?

My intention was to implement a watch on $validator.errors, so that any error that arises gets logged, To achieve this, I checked the length of errors and stored self.errors.all() in a variable, However, I'm curious if it's possible to directly ...

Eliminating and restoring the background in a form field when it is in focus

/* This function clears the default text in a field when clicked on */ $('#edit-field-activity-notes-und-0-value') .each(function() { $(this).data('default', this.value); var mybackground = $(this).css('backgroun ...

CSS to Reverse Align Navigation Bar Text

I'm currently working on my first website and I've encountered a problem with the Navigation Bar. Using CSS rules to align the bar, I noticed that when I apply float:right;, the text floats to the right but ends up aligning backwards on the bar. ...

Limiting page entry with passport.js and express middleware

My server is set up to authenticate user login. I have successfully redirected users to the success page after authentication (and back to the login page if it fails). However, I am facing an issue with using my own express middleware to restrict access fo ...

The PHP code embedded within the HTML document and triggered by an AJAX request failed to

Here is an example of my ajax call: function insertModal(link) { $.ajax({ url: link, cache: false, dataType: "text", success: function(data) { $("#modalInput").html(data); }, error: function (request, status, error) { ...

Guide to building a nested React component

My custom dropdown component requires 2 props: trigger (to activate the dropdown) list (content to display in the dropdown) Below is the implementation of my component: import { useLayer } from "react-laag"; import { ReactElement, useState } fr ...

Maximizing the efficiency of React.js: Strategies to avoid unnecessary renders when adding a new form field on a webpage

Currently, I have a form that consists of conditionally rendered fields. These components are built using MUI components, react-hook-form, and yup for validation. In addition, within the AutocompleteCoffee, RadioBtnGroup, and TxtField components, I have i ...

I'm perplexed as to why my webpage displays differently across various browsers

Currently, I am utilizing the Yahoo CSS reset and all my CSS is based on pixel values rather than relative units like ems. Interestingly, there seems to be a discrepancy in the position of the bottom right corner of the form-containing div between Chrome a ...

Applying CSS to align the first line to the left and right, while ensuring that wrapped lines are aligned to the

Struggling with CSS to align drink names and descriptions on a bar's menu. Want the name left aligned and the description right aligned, even if wrapped lines are also right aligned. Current progress can be seen at http://jsfiddle.net/H96XQ/ CSS: . ...

Challenge implementing custom javascript to display categorical/string features on Shiny slider

I'm attempting to design a unique Shiny slider that represents the months of the year. My desired outcome is for the slider to display the names of the months as strings, rather than numeric values where 1 corresponds to January, 2 corresponds to Febr ...

Enable compatibility with high resolution screens and enable zoom functionality

My goal is to ensure my website appears consistent on all screen sizes by default, while still allowing users to zoom in and out freely. However, I've encountered challenges with using percentages or vh/vw units, as they don't scale elements prop ...

Can you tell me how to add a variable to an array of objects in JavaScript?

I am currently engaged in a small project aimed at: Reading data from a CSV file (such as employee names and shifts) Displaying this data on FullCalendar. How can I incorporate the CSV result into this line of code: { id: 'a', title: 'Audi ...

Troubleshooting: No data returned from getStaticProps in Next JS

I'm currently working on a project using Next.js with context API and styled components, but I'm facing issues with getting getStaticProps to work properly. After researching online, I found suggestions about the custom _app, which I already hav ...

Testing a Vue.js/Node.js application using Websockets

I'm working on a Vue project (version 3.0.3) integrated with a Node.js server. Can you provide guidance on how to conduct unit testing for this setup? The application is a game that relies on web-sockets for communication. ...

Trouble with minification in Sencha cmd 5

I've been attempting to compress a Sencha 5 project using Sencha CMD, but I keep experiencing failures. sencha generate app -ext demoApp ./demoApp Then, in an effort to compress the application, I entered the following command: sencha app build ...

When you apply margins in CSS and HTML, it can cause elements to break out of the row alignment

I'm struggling with my html code that contains elements arranged in rows: <div class = "row"> <div class="col-sm-3 cont-box"> <h1>Title1<h1> </div> <div class="col-sm9 cont-box"> <img src="onepic.jpeg" class=" ...