Search code examples
javascriptjquerycss-animationsonmouseover

How to play an Animation with JS


Im coding a fade-in and fade-out text on button hover... and I have to call an animation onhover... how I can do it?

const button = document.getElementById("btn");
const disp_text = document.getElementById('disp_text');

button.onmouseover = function(){
 //Here goes the animation to play
 disp_text.innerText = "Next";
}

I've Tried:

const button = document.getElementById("btn");
const disp_text = document.getElementById('disp_text');

button.onmouseover = function(){
 animation.Play("fadein");
 disp_text.innerText = "Next";
}

But nothing...

If someone can help, I would be very grateful...


Solution

  • .play() will only work if you have mentioned how to animate

    const button = document.getElementById("btn");
    const disp_text = document.getElementById('disp_text');
    
    button.onmouseover = function(){
     disp_text.innerText = "Next";
     
     const animation = disp_text.animate(
    [
      { opacity: 0 },
      { opacity: 1 }
    ], {
      easing: 'ease',
      duration: 2000
    });
    
     animation.play();
    }
    <button id="btn">Hello</button>
    <p id="disp_text"></p>