Mark Nolan
Mark Nolan

Reputation: 167

jquery pulsating text

I'm using jquery to pulsate text. All fine - but I can't get my head around something: I would only like to pulsate x-number of times and then stop. I'm using the following code to pulsate a class:

$(document).ready(function() {
  function pulsate() {
    $(".pulsate").
      animate({opacity: 0.2}, 1000, 'linear').
      animate({opacity: 1}, 1000, 'linear', pulsate);
  }
  pulsate();
});

Any ideas how this can be achived? Probably one line of code...?!

Upvotes: 2

Views: 9164

Answers (1)

Nick Craver
Nick Craver

Reputation: 630597

The simplest way is to just count:

$(document).ready(function() {
  var i = 0;
  function pulsate() {
    if(i >= 3) return;
    $(".pulsate").
      animate({opacity: 0.2}, 1000, 'linear').
      animate({opacity: 1}, 1000, 'linear', pulsate);
    i++;
  }
  pulsate();
});

Try it here. Or, queue up all the animations at once in a for loop, like this:

$(function() {
  var p = $(".pulsate");
  for(var i=0; i<3; i++) {
    p.animate({opacity: 0.2}, 1000, 'linear')
     .animate({opacity: 1}, 1000, 'linear');
  }
});

Try that version here.

Upvotes: 11

Related Questions