s4y
s4y

Reputation: 51705

Why can't I change the speed of a CSS animation by adding a class?

I defined an animation like this:

@-webkit-keyframes pan {
    from {left: 10%;}
    to {left: 20%;}

}

#dot {
    background: black;
    width: 10px;
    height: 10px;
    position: absolute;
    top: 20%;
    border-radius: 100%;
    -webkit-animation: pan 10s linear infinite;
}

body.fast > #dot {
    -webkit-animation: pan 1s linear infinite;
}

When I use JavaScript like this to change #dot's class:

document.body.classList.add('fast');

Nothing happens! What's up here?

Example: http://jsbin.com/buqowizi/2

Upvotes: 2

Views: 97

Answers (3)

AD7six
AD7six

Reputation: 66288

The specification for css animations states:

Once an animation has started it continues until it ends or the animation-name is removed

As such with an animation time of "infinite" it can't be modified once started without modifying the animation-name.

Here's a jsfiddle demonstrating a change in speed (though it's not smooth, there's probably a more appropriate solution) the premis being:

div.reset {
    -webkit-animation: none; # <-
}
div.slow {
    -webkit-animation: pan 10s linear infinite;
}
div.fast {
    -webkit-animation: pan 1s linear infinite;
}

Change the class of the element so that the animation resets, and then start a new animation with a different duration.

Upvotes: 4

valerio0999
valerio0999

Reputation: 12136

here's a jsbin: http://jsbin.com/buqowizi/6/edit?html,css,js,output

i modified css, html and javascript to make it work. your code was a bit buggy

Upvotes: 0

meadowstream
meadowstream

Reputation: 4141

It's enough to specify the duration only:

-webkit-animation-duration: 1s;

And this javascript code should work:

var dot = document.getElementById('dot');
var fast = false;

speed.addEventListener('change', function(e){
  if(!fast) {
      dot.classList.add('fast');
      fast = !fast;
  } else {
      dot.classList.remove('fast');
      fast = !fast;
  }
});

Demo

Upvotes: 0

Related Questions