1.21 gigawatts
1.21 gigawatts

Reputation: 17746

How to get an animation by name

Is there a way to get the an animation style rule by name?

I have this animation:

@keyframes fadein {

    0% {
        opacity: 1;
    }
    37.5% {
        opacity: 1;
    }
    50% {
        opacity: 0;
    }
    87.5% {
        opacity: 0;
    }
    100% {
        opacity: 1;
    }

}

And I'm using it like so in multiple places:

#MyElement {
    animation: fadein 5s linear 0s infinite;
    pointer-events: none;
}

I want to change the animation duration dynamically from 5s to 1s using JavaScript.

If I want to change the animation duration without knowing where it is being used how would I do it?

Upvotes: 0

Views: 152

Answers (1)

ksav
ksav

Reputation: 20821

You can change the animation-duration like this:
myElement.style['animation-duration'] = value;

const myAnimatedElements = document.querySelectorAll(`.anim`)

const mySelect = document.querySelector(`select`)

mySelect.addEventListener(`change`, handleSelectChange)

function handleSelectChange(event) {
  const value = event.target.value
  myAnimatedElements.forEach(el => el.style[`animation-duration`] = value)
}
@keyframes fadein {
  0% {
    opacity: 1;
  }
  37.5% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
  87.5% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

.anim {
  animation: fadein 5s linear 0s infinite;
  pointer-events: none;
}
<select>
  <option value="5s">5s</option>
  <option value="4s">4s</option>
  <option value="3s">3s</option>
  <option value="2s">2s</option>
  <option value="1s">1s</option>
  <option value="0.5s">0.5s</option>
</select>

<div class="anim">Animated</div>
<div class="anim">Animated</div>
<div class="anim">Animated</div>
<div class="anim">Animated</div>
<div class="anim">Animated</div>
<div class="anim">Animated</div>

Upvotes: 2

Related Questions