jQuery - Multiple click events

1833 views javascript
-2

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.

answered question

2 Answers

6

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.

posted this
3

You need to remove the CSS class once the animation is over.

$('h1').click(function() {
  $('h1').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.

  • one() is an event handler attachment that ensures the handler is executed just one time.

  • For on() have a look to the jQuery documentation.

posted this

Have an answer?

JD

Please login first before posting an answer.