Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click event lost after css animation

For a laugh I have put a Google-esk barrel roll on one of my sites.
All works fine on the first click of the selected element, but it won't fire again after that.

I have tried .click, .on('click', function() {}) and neither work.
Any ideas on how to fix and why this is happening?

Basic jsFiddle here

Source code example;

<html>
    <head>
        <title>
            Roll Me
        </title>

        <style type="text/css">

        </style>

        <script>
        $(function() {
            $('#roll').on('click', function() {
                $('body').css({
                    "-moz-animation-name": "roll",
                    "-moz-animation-duration": "4s",
                    "-moz-animation-iteration-count": "1",
                    "-webkit-animation-name": "roll",
                    "-webkit-animation-duration": "4s",
                    "-webkit-animation-iteration-count": "1"
                });
            });
        });
        </script>
    </head>
    <body>
        <div id="roll">
            <h1>click me</h1>
        </div>
    </body>
</html>
like image 494
Rooneyl Avatar asked Apr 02 '15 14:04

Rooneyl


2 Answers

You need to remove the animation that you applied after it has finished and then re-add it on subsequent clicks.

var $body = $('body');

$('#roll').on('click', function() {
    $body.addClass('barrel-roll');
});

$body.on('animationEnd webkitAnimationEnd mozAnimationEnd',function(e) {
    $body.removeClass('barrel-roll'); 
});
@-webkit-keyframes roll {
from { -webkit-transform: rotate(0deg) }
to { -webkit-transform: rotate(360deg) }
}

@-moz-keyframes roll {
from { -moz-transform: rotate(0deg) }
to { -moz-transform: rotate(360deg) }
}

@keyframes roll {
from { transform: rotate(0deg) }
to { transform: rotate(360deg) }
}

.barrel-roll {
 -webkit-animation-name: roll;   
 -webkit-animation-duration: 4s;
 -webkit-animation-iteration-count:1;
 -moz-animation-name: roll;   
 -moz-animation-duration: 4s;
 -moz-animation-iteration-count:1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="roll">
    <h1>click me</h1>
</div>
like image 121
Adam Avatar answered Nov 09 '22 07:11

Adam


That's because by that point the body element already has that CSS styling applied. The way to fix it is to remove the style properties from your body element:

setTimeout(function() {
    $('body').removeAttr('style');
}, 4000);

I've used setTimeout here to ensure the style attribute gets reset only after your animation has completed (after 4 seconds).

JSFiddle demo.

like image 3
James Donnelly Avatar answered Nov 09 '22 07:11

James Donnelly