The animation of a disappearing div with CSS is not stopping when hovering over it

Hello, I've been working on a snackbar feature that appears and disappears on a set timer but also needs to pause when hovered over. Unfortunately, the current setup with setTimeout and useState is causing issues with this functionality.

I have looked online for solutions to this problem but haven't found any that work for me yet. Any assistance or guidance would be greatly appreciated.

Check out the code here

App.js

const App = () => {

  const [showSnack, setShowSnack] = useState(false);

  const toggle = () => {
    setShowSnack(true);
    setTimeout(() => {
      setShowSnack(false);
    }, 1000);
  }

  return (
    <div>
      <button onClick={toggle}>Toggle</button>
      <Snack show={showSnack} />
    </div>
  );
}

render(<App />, document.getElementById('root'));

Snack.js

const Snack = ({show}) => {

  return(
    <div className={`my-snack ${show ? 'show' : ''}`}>My Snackbar</div>
  );
}

index.css

.my-snack {
  position: fixed;
  width: 100%;
  height: 500px;
  background: lightgray;
  bottom: 0;
  visibility: hidden;
  cursor: pointer;
}

.my-snack.show {
  visibility: visible;
  animation: fadein 0.5s, fadeout 0.5s 9.6s;
}

.my-snack:hover {
  animation-play-state: paused;
}

@keyframes fadein {
  from {bottom: -500px;}
  to {bottom: 0;}
}

@keyframes fadeout {
  from {bottom: 0;}
  to {bottom: -500px; opacity: 0;}
}

Answer №1

If you're looking for a solution, consider utilizing the onAnimationEnd event instead of relying on a timer. This method allows you to manage timing through CSS and ensures that your component reacts appropriately once the animation completes.

<Snack
  show={showSnack}
  onAnimationEnd={(e) => {
    setShowSnack(false)
  }}
/>

const Snack = ({ show, onAnimationEnd }) => {
  return (
    <div
      className={`my-snack ${show ? 'show' : ''}`}
      onAnimationEnd={(e) => {
        if (e.animationName === 'fadeout') {
          onAnimationEnd(e)
        }
      }}>
      My Snackbar
    </div>
  )
}

An important point to note with this approach (specifically for your scenario) is that you need to be aware of the animation name in JavaScript when dealing with multiple animations concurrently. For example: (e.animationName === 'fadeout')

For an example, check out: https://stackblitz.com/edit/react-szkq7w

Answer №2

It appears that there may be some confusion between the CSS animation for fading in the snackbar and actually showing or hiding the snackbar itself. One approach could be to utilize onMouseOver and onMouseOut events to pause and resume the timer accordingly. These functions would need to be passed to the Snack component and set on the DOM element.

  const timer = useRef(null);

  const clearSnackTimer = () => clearTimeout(timer.current);

  const startSnackTimer = () => timer.current = setTimeout(() => setShowSnack(false), 1000);

  const toggle = () => {
    setShowSnack(!showSnack);
    startSnackTimer();
  };

  return (
    <div>
      <button onClick={toggle}>Toggle</button>
      <Snack show={showSnack} onMouseOver={clearSnackTimer} onMouseOut={startSnackTimer} />
    </div>
  );

There still seems to be an issue with the fadeout transition, but this solution addresses the requirement of pausing the hiding of the snackbar when hovering over it, if that is your intended functionality.

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

Express application encountering an issue when trying to render a live chart with flot in the Jade client

Encountering an issue while trying to visualize real-time data using a flot chart. The client code displays the following error: Uncaught Invalid dimensions for plot, width = 1584, height = 0 I am perplexed by the fact that the height is showing as 0. ...

Tips for eliminating the draggable item's shadow in Angular

Is there a way to remove the shadow seen under the backdrop when dragging an item in the Bootstrap modal dialog? In the image provided, I am trying to drag the "Personal Details" button..https://i.stack.imgur.com/uSNWD.png ...

Trouble accessing files in the assets folder of Angular 2

I am encountering a 404 error when attempting to access a local file within my application. I am unable to display a PDF that is located in a sub-folder (pdf) within the assets folder. I am using CLI. <embed width="100%" height="100%" src="./assets/pdf ...

The concept of position() is often mistaken for a function

I am currently developing a slider and have included the code below: $(document).ready(function() { // MAKE SLIDER WIDTH EQUAL TO ALL SLIDES WIDTH var totalWidth = 0; $('.slide').each(function() { totalWidth = totalWi ...

Navigating the issue of "Experiencing additional hooks rendered compared to the previous render"

I'm currently in the process of developing a small application where certain elements will be nested within one another. My approach involves segmenting each component into its own file (children), returning a function with two components in each Rend ...

Just launched NextJS on Firebase, encountering a 403 Forbidden Error

Recently, I successfully deployed my NextJS app on Firebase Hosting and Firebase Functions. However, upon visiting my website after deployment, I encountered an unexpected page. Screenshot This is how my firebase.json file looks: { "hosting&qu ...

Expanding VS 2013: Effective management of classes through item customization

Trying to accomplish a somewhat complex task, I have dedicated hours to searching for the appropriate documentation with no success. The goal is for Visual Studio to generate some JavaScript code and place it in a specific folder, starting from: Performi ...

Our express.js does not recognize GET requests from routers

When placeholders and predefined routes coexist in the same location, the predefined routes are never called if the placeholder was declared before them. For example: router.get("/:id", fetchEntry) router.get("/fancy-action/", doSomet ...

The Dockerfile for Next13 is unable to locate the server.js file

When using the official Dockerfile from Next with the examples provided, I encounter an error while trying to build the app using a Dockerfile and docker-compose. b78-client-1 | node:internal/modules/cjs/loader:1078 b78-client-1 | throw err; b78-client ...

When creating routes in Express 4.* using node.js, it is essential to use the root directory

Completely new to the world of node.js, I find myself navigating through an outdated and partially functioning course on udemy.com. In previous modules, I managed to successfully receive content through routes like app.get('/vegetables',functio ...

What is the best way to update a specific value in an object without affecting the rest of

Below is a data object: { name: "Catherine Myer", age: 23, birthday: "august" } If I want to pass this data as a prop to a component, but also change the age to 24, how can I do that? <NextPage data={author.age = 24}/> The ...

How to Transform a Navigation Bar into a Carousel

I am creating a website that is designed to be responsive. Currently, I have a horizontal navigation bar which collapses into a drop-down menu when the screen size decreases. When each tag in the menu is clicked, a different image loads into a designated ...

ReactJS incorporates multiple CSS files

I am currently working on developing a Single Page Application using ReactJS. However, I am facing an issue with styling. Currently, I have created 3 different pages (with the intention of adding more in the future), each having its own CSS file that is im ...

Transforming strings of HTML into objects in the DocX format

After developing a TypeScript script that transforms a JSON string into a Word Doc poster using Docx, I encountered a hurdle. Certain sections of the JSON may contain HTML tags, such as <br/>, <i>, <p>, and I need a way to pass the stri ...

Listener for 'timeupdate' event on video doesn't retain values

My html5 video event listener is designed to pause the video at a specific time while the user participates in a quiz. The first 'lesson' works fine, and the second video also appears to add the listener with the correct pause time. However, when ...

Refresh your jQuery function without the need to reload the entire page

Is there a way to update a function's parameters without reloading the entire page? For instance, if I modify the 'style' dropdown value as shown in the URL image, can it be passed to the accordion function so that the accordion's color ...

Why won't my dropdown menu work properly with JavaScript on certain pages?

Being new to javascript, I encountered an issue with a function that I recently modified. When a user selects "Yes" from a dropdown menu, it should generate 3 text boxes within a specific div area. Below is the code for my form dropdown: <select name= ...

What is preventing bots and crawlers from detecting Next.js meta tags?

I'm currently using Next.js with Typescript and MongoDB to retrieve data. I'm encountering difficulties in rendering the page because the crawler is unable to detect the meta tags. For instance, Bing Search Engine claims that Title and Meta desc ...

Rearrange the array so that any empty values are placed at the end

I am trying to arrange all empty values at the end of an array. The code below demonstrates my attempt: 1) This code moves all empty values to the end of the array, but it does not sort the other values accordingly. var dateArray = [ '',&apos ...

Troubleshooting event binding problems with jQuery

<div id="parent"> <div id="children"> </div> </div> If we attach the same events to both parent and children elements: $("#parent").live({ mouseenter : Infocus , mouseleave : Outfocus }); $("#childre ...