Search code examples
reactjstailwind-cssframer-motion

Framer motion delay on onMouseLeave


I am try to create a hover effect by using onMouseEnter and onMouseLeave, I have a parent div when a onMouseEnter triggered on the div the two child div will translateX from -100 to 0, on child div have a delay of 0.4s. You can see the sandbox here: https://codesandbox.io/p/devbox/g7g8cr?migrateFrom=zwdwr9,

When onMouseLeave the first child moving left fast before second child.

I need when onMouseLeave the first div move left after the second completely moved left.


Solution

  • You can change the delay of the children div based on the hover state like so:

    const STAGGER_DELAY = 0.4;
    
    ...
    
    <motion.div
      initial={{
        x: -130,
      }}
      animate={isHover ? { x: 130 } : {}}
      transition={{ duration: 0.5, delay: isHover ? 0 : STAGGER_DELAY }}
      className="size-20 bg-green-500 absolute top-10 left-10"
    ></motion.div>
    
    <motion.div
      initial={{
        x: -150,
      }}
      animate={isHover ? { x: 0 } : {}}
      transition={{ duration: 0.5, delay: isHover ? STAGGER_DELAY : 0 }}
      className="size-20 bg-yellow-500 absolute top-10 left-10"
    ></motion.div>
    

    I created this working example. There are two components in my example, <Basic /> and <Advanced />. I created the Advanced component to showcase how you can take advantage of Framer Motion's stagger transition so that you don't have to worry about the orchestration of the children divs. This makes it a lot easier to add more children divs if you wanted.