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

Limit jQuery script to operate exclusively on a single page

Despite the abundance of answers to similar questions, my lack of JS skills hinders me from implementing them in my specific case. On my WordPress site, I have a script that changes the navigation bar's color when scrolling down to the #startchange CS ...

How to Utilize USB Devices with Node-Webkit?

I am in the process of creating a node-webkit application that must be compatible with all three major desktop operating systems (Windows, Mac, and Linux). My goal is to establish a connection between my app and a USB device that is plugged in, but I am en ...

Struggling with making changes to a instantiated "this" object within a pseudo javascript class

If you scroll down to the bottom of this post, you'll find a workaround or possible solution. I've been grappling with understanding how pseudo classes work together to achieve the task I'm attempting (explained in the code below). It might ...

Is it advisable to use an autosubmit form for processing online payments?

Situation: In the process of upgrading an outdated PHP 4 website, I am tasked with implementing an online payment system. This will involve utilizing an external payment platform/gateway to handle transactions. After a customer has completed their order ...

CSS animation for input range slider

Is there a way to create smoother animations for the input[type="range"] element, especially when dealing with short audio files? You can check out my Codepen where I've been experimenting with solutions using a short audio file: Codepen Link I am s ...

The module 'iap_verifier' could not be located

Setting up a new server using the following repository - https://github.com/surespot/web-server. I have successfully installed node.js, npm, CoffeScript, and all required dependencies. apt-get install nodejs npm npm install -g <a href="/cdn-cgi/l/email ...

What steps can be taken to ensure that any new elements generated by JavaScript do not disappear upon refreshing the page

I am currently working on a project where I am creating a list by collecting user information and storing it in a MySQL database. When the user clicks the 'add' button, a new element is added to the bottom of the existing list which is coded in H ...

Collaborating and utilizing React Components in multiple projects

Seeking advice on a conceptual dilemma. I am managing two projects that are built on separate react services, and there are many components that could be shared between them. How can I create a dynamic shared-component project that can be accessed simult ...

Whenever I implement JavaScript validation on my HTML page, it causes the page to become un

Whenever I try to enter more than 30 to 40 characters in the password input field on my HTML page, all web browsers become unresponsive. This issue persists even if I modify the minimum length and other requirements to 50. I am new to JavaScript. <!D ...

A handy tip for sending a response once a for each loop has finished executing

It is important that Response.json executes only after the foreach loop has completed its execution. var todoarr = (req.body.data) ? req.body.data : undefined todoarr.forEach(function(element) { if(element.done == true) { TodoS ...

In JavaScript, generate a new column when the text exceeds the height of a div

Is it possible to create a multicolumn layout in HTML that flows from left to right, rather than top to bottom? I am looking to define the height and width of each text column div, so that when the text overflows the box, a new column is automatically ge ...

How to properly declare an explicit injector when using the resolve parameter in $routeProvider?

$routeProvider resolve feature in AngularJS allows for injecting additional dependencies to the controller function. How can we combine this with explicit dependency injection declaration? Example: angular.module('myModule', []) .config(func ...

Leveraging Redux Toolkit for managing extensive arrays of latitude and longitude coordinates

In my project using React Native and Redux Toolkit, I am working on tracking a user's location on a map. The problem arises when the user moves more than 2 meters - the redux dispatch triggers to update the coordinates in the allCoords array. This ope ...

When using Firebase hosting in conjunction with ReactJS, it may encounter difficulties when attempting to process redirects from

As a beginner in Reactjs and Firebase web hosting, I have encountered an issue with Sketchfab OAuth2 integration. In order to authenticate with Sketchfab, I must provide a redirect link such as However, my use of react-router results in URLs containing a ...

Leveraging jQuery template for JSON visualization

I've been struggling for days to understand how to render JSON data using jQuery templates with no luck. I was hoping someone could help me figure out where I'm making a mistake. The JSON data I am working with looks something like this: [{"pk" ...

How to transform the Material UI functional component Mini variant drawer into a class component in ReactJS

I have been working with the mini variant drawer component from the official material-ui website and I am encountering some issues when trying to convert it into a class component. The errors seem to be related to hooks and are occurring within the node ...

Highlight the menu item when you reach a specific section

I am facing difficulties in creating a scrolling menu that highlights the respective item when a specific section is reached. As a beginner in design, I am struggling to achieve this effect. Any insights or guidance on how to implement this would be grea ...

Send information to the dialogue box upon clicking

After clicking on my accordion, I expect the information in this line to be transferred to the dialog box form. However, I am not seeing any data being passed to the form. Why isn't the form receiving the data? import React, { useEffect, useStat ...

Navigating the process of returning a list from an AJAX method to a view through a controller in ASP.NET MVC

I need to retrieve a list from my controller and pass it to the view. Currently, I have the following script: function fetchNames(_id, _name) { $.ajax({ type: 'Post', url: 'GetNames/', data: { id: _id, name: _name}, su ...

Having trouble updating a text field on an event using JavaScript - value not defined

When I change the select option, my goal is to dynamically set the value of the input using JavaScript. However, I am encountering an issue where the value becomes undefined. Below is a snippet from my HTML (JSP) file: <body> <center>< ...