0

I've implemented the solution from This thread and it still only runs once.

Code:

    const ButtonClickFunction = (e,id)=>{
    e.preventDefault()
    var el = document.querySelector(`.location-${id}`)

    el.style.animation = '';
    el.style.animation = "addition 1s";

}

From what I can tell, every time I click the button the elements animation is cleared, then set to the animation I want. But still, it only runs once and then never works again. I really hoping to just do this with javascript, as adding a class and then taking it away just seems clunky and not the best practice. I'm using React as a FE framework if that matters

edit:SOLUTION

    var el = document.querySelector(`.location-${id}`)

    el.style.animation = "addition 1s 3";

    el.addEventListener('animationend', ()=>{
        el.style.animation = ""
    })

Like one user stated, the browser will ignore back to back assignments and just optimize to run that final assignment call. To get around this, use the eventlistener to trigger the 'reset' once the animation has ended.

I'm still of the opinion that adding classes, taking away classes,and using a setTimeout to 'reset' the animation is awkward and clunky.This solution is just a few lines of code and doesn't hurt maintainability having to scroll through endless amounts of classes if you have many animations you want your users to trigger.

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/animationend_event

Officer_Narc
  • 195
  • 3
  • 15
  • Many would argue that most of the animation in CSS is actually the preferred way of doing things. – Victor Mar 31 '20 at 22:42
  • The CSS would seem essential to solving this. – see sharper Mar 31 '20 at 23:26
  • 1
    Your solution does not look like any in the thread you linked, I suggest you take another look! Essentially the reason is that when you set the `el.style` twice in quick succession like that, the brower will optimise it for one action, which is the final state, which means no change occurs. You can solve this by using a timeout like the thread you linked suggests, or using `window.requestAnimationFrame` - [here is a thread](https://stackoverflow.com/questions/60677975/how-can-i-restart-a-css-transition-as-soon-as-it-ends-using-standard-javascriptt) which might be able to help you with that. – lawrence-witt Mar 31 '20 at 23:30
  • Thanks for the insight Lawrence, you really seemed to understand my lack of implementation and gave a great explanation on why mine wasn't working. Definitely pushed me in the right direction. – Officer_Narc Mar 31 '20 at 23:54

0 Answers0