JQuery animated bounce only runs once

I am trying to bounce the typewriter image each time somebody clicks on it.

My JS codes are:
$(document).ready(function(){
$(“img”).click(function(){
$(this).addClass(“animated bounce”);
genQuote();
});
});

Sadly it only bounces the first time the image is clicked. Subsequently, only the genQuote() function that runs each time the image is clicked.

My full codepen is here https://codepen.io/kwidyani/pen/prmVwa

Please help me! Thank you!

This works…

$(document).ready(function(){
  $("img").click(function(){
     $("img").addClass("animated bounce");
     genQuote();
    setTimeout(function(){
       $("img").removeClass("animated");
       $("img").removeClass("bounce");
    }, 1000);

  });
});

You add the class, the image bounces. But it will only bounce once (because after that, the class is still added.)

So you need to remove the bounce and animated class. So the next time you add it again, the image will bounce again.

But you don’t want to remove the bounce too quickly because then you won’t see the animation.

so you put that inside a delay function. Problem is “this” doesn’t work inside the setTimeout function. So I just targed the “img” tag specifically.

Best to assign an “id” to the image, and target the “id” in the addClass and removeClass function. I’ll leave that as exercise for you.

1 Like

Thank you! What a handy function to know!
That actually gave me the idea to delay the display of the quote. The idea is, the typewriter bounces, and only after it stops bouncing that the quote will be displayed. I thought it would be as simple as adding another setTimeout function, but the effect I want is not happening. :anguished:

$(document).ready(function(){
$("#machine").click(function(){
$(“img”).addClass(“animated bounce”);

setTimeout(function(){
   $("#machine").removeClass("animated");
   $("#machine").removeClass("bounce");
}, 1000);
setTimeout(genQuote(), 5000);

});
});

Hey. You may try adding your class before your genQuote and then removing it inside the setTimeout. Like so:

    $("img").addClass("animated bounce");
    setTimeout(function(){
      $("img").removeClass("animated bounce");
       genQuote();
    }, 1000);

Hi,
You should remove the () after genQuote() when using it in setTimeout like this:

setTimeout(genQuote, 5000);

See this Stack Overflow answer for why.

1 Like

Thank you! That did it!

Thank you! Is this just something we need to remember or is there a logic behind not having the ()?

Given a function, for example:

sayhello = function() { console.log('hello') };

If you use “sayhello()”, you’ll be executing the function itself and getting it’s return value (if any). In your browser console, you’ll see

sayhello()
> hello

If you use “sayhello”, you’re not executing the function, but returning the actual contents/code of the function itself. In your browser console you’ll see

sayhello
> ƒ (){console.log('hello')}

Try it.

2 Likes