Reputation: 439
I have a problem. I just started learning jQuery, my first experience with javascript at all. And I want to make an element animate on click, and I did make that work:
HTML:
<h1>Testing</h1>
I'm using Animate.css to make some animations happen on click. Here's my jQuery:
$('h1').click(function (e) {
$('h1').addClass('animated bounce');
});
What I want to achieve is that when I click 2nd time, the animation happens again, in fact, I want to remove the animated bounce class and add it again, that way the animation will happen again.
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.0/animate.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>
<body>
<h1>Testing</h1>
<script>
$('h1').click(function (e) {
$('h1').addClass('animated bounce');
});
</script>
</body>
And please tell me if I'm doing the code the way it should be, I mean if the syntax is fine, I've seen codes with $(this) and I'm not sure what that is, also I've seen something like .on('click')
Thank You.
Upvotes: 3
Views: 838
Reputation: 7315
You need to remove the CSS class once the animation is over.
$('h1').click(function() {
$(this).addClass('animated bounce').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
$(this).removeClass();
});
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.0/animate.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<h1>Testing</h1>
For the rest, your syntax is fine.
Some notes:
e
is an object based on Event describing the event which has occurred. It is optional. If you don't need data from the event you can skip it.
$(this)
is a jQuery object. In the context of the callback, it is the element which invokes the function. In JavaScript, the this
keyword is a very important and complex topic. You can read about it in MDN and here in SO.
one()
is an event handler attacher that ensures the handler is executed just one time.
on()
is other attacher. Have a look to this other SO question to learn when to use click()
or on('click')
.
Upvotes: 6
Reputation: 44145
Do this:
$('h1').on("click", function() {
$(this).addClass('animated bounce');
setTimeout(()=> $(this).removeClass('animated bounce'), 1000);
});
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.0/animate.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>
<body>
<h1>Testing</h1>
</body>
You use the toggleClass
method - it toggles whether the element has the class, as the name would suggest.
Upvotes: 1