"For a Limited Time!!" Adding a CSS class for a short duration.
I recently had a reason to create a visual effect in which a bit of text pulsed with a bright color once. I wanted to use CSS3 animation to be kind to the CPU and provide a smooth transition from the text's normal color to the highlight color. I could have used jQuery's animation mechanism, which steps through states at 13 millisecond intervals by default. My plan was to create a callback function to remove the class after a pulse from normal to highlighted and back to normal. I came up with two ways to add the class to an element, the remove it a second later: using a native JavaScript setTimeout (jsFiddle), and using the jQuery animation queue (jsFiddle). I tried to get the jQuery UI Effects enhancements to work (see line 4321 in jQuery UI 1.8.16), but it didn't function properly for some reason.
Here's a little bit of HTML:
<span id="pulseable">Some Pulsating Text</span>
<input type="button" id="run" value="Run Example"/>
Here's the stylesheet that creates the pulsating text:
#pulseable {
color: black;
}
.pulse {
-moz-animation: pulse 1s infinite linear;
-webkit-animation: pulse 1s infinite linear;
}
@-moz-keyframes pulse {
0% { color: black; }
50% { color: yellow; }
100% { color: black; }
}
@-webkit-keyframes pulse {
0% { color: black; }
50% { color: yellow; }
100% { color: black; }
}
Here's the old-school JavaScript:
var p = document.getElementById("pulseable");
document.getElementById("run").onclick = function () {
p.className = "pulse";
window.setTimeout(function () { p.className = ""; }, 1000);
return false;
};
And here's a more convenient way using jQuery, which is nice because it stops any pending queued events on the callback:
$("#run").bind("click", function (event) {
$(this).prev().addClass("pulse").delay(1000).queue(function () {
$(this).stop().removeClass("pulse");
});
});
Posted 11/2/11 @ 5:12 PM by Joseph Lamoree