Ari Seyhun
Ari Seyhun

Reputation: 12521

Instantly end CSS animation with JavaScript

I have an input box with a CSS animation assigned to it, so when the page loads, it has a nice fade-in animation.

The CSS:

#search-box {
    /* ... */
    animation: 2s fade-in
}

@keyframes fade-in {
    from { opacity: 0 }
    to { opacity: 1 }
}

In some cases when the page is loaded (when a URL param exists), I'd like the input box's CSS animation to stop and instantly put the opacity to 1.

I've tried messing around with animation-play-state and attempting to override the opacity with !important but have had no luck.

Javascript:

let endAnimation = // ... boolean
if (endAnimation) {
    let elem = document.getElementById('search-box');
    // End the animation and set opacity to 1 somehow...
}

HTML:

<input id="search-box">

Upvotes: 1

Views: 313

Answers (1)

Temani Afif
Temani Afif

Reputation: 272806

You can make the animation in a separate class, and simply remove this class to stop the animation:

let stop = function() {
  let elem = document.getElementById('search-box');
  elem.classList.remove('animate');
}
#search-box {}

.animate {
  animation: 5s fade-in;
}

@keyframes fade-in {
  from {
    opacity: 0
  }
  to {
    opacity: 1
  }
}
<input id="search-box" class="animate">
<button onclick='stop()'>stop!</button>

Or simply unset the animation property:

let stop = function() {
  let elem = document.getElementById('search-box');
  elem.style.animation='unset';
}
#search-box {
  animation: 5s fade-in;
}

@keyframes fade-in {
  from {
    opacity: 0
  }
  to {
    opacity: 1
  }
}
<input id="search-box" class="animate">
<button onclick='stop()'>stop!</button>

Upvotes: 3

Related Questions