LoginSignup
22
22

More than 5 years have passed since last update.

あるボタンを押した時のアニメーション効果を連打しても確実に付けさせたい

Last updated at Posted at 2016-08-07

あるボタンを押した時に、
ぽよんと反応するようなアニメーション効果を与えたい。
その要素を押したら、例えば .click-animationのような、ぽよんとするCSSアニメーションを付けたクラスを、付与させる事が多いが、そんな時の実装MEMO。

要素を押した時に、.click-animationが既に付与されていたら、削除してから付与しないとアニメーションしなく、また削除して即付与してもアニメーションしないので、setTimeout()などで適当な一定時間待って付与する事が多かった。

$(target).removeClass('click-animation');
setTimeout(function() {
    $(target).addClass('click-animation');
}, 10);

もしくは、webkitAnimationEndなどを使って、アニメーション後にクラス削除などしていた。

$(target).addClass('click-animation');
$(target).on('webkitAnimationEnd', function() {
    $(target).removeClass('click-animation');
});

ただこれだと連打した場合に反応してくれない場合がある。
結論、requestAnimationFrameを使うと良さそう。

$(target).removeClass('click-animation');
requestAnimationFrame(function() {
    $(target).addClass('click-animation');
});

これだと高橋名人ばりに連打した場合も確実にアニメーション効果を与える事ができた。
ブラウザの次のレンダリングフレームを待ってクラス付与してるから確実ということだろうか。

Google I/O 2016の実装サンプルとかでも、requestAnimationFrameを使った要素の付与や削除をやってるようだった。

22
22
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
22