jQuery Blinking Elements

Set the interval and blink elements forever or for a set amount of time.

by dledle2

HTML

<form method="post">
    <p class="myClass">Blink 25 times in 5 second intervals:
        <input type="text" name="username" />
    </p>
    <p>I will do the same:
        <textarea class="myClass"></textarea>
    </p>
    <p><span class="myClass">Me too!</span>
    </p>
    <input type="submit" name="submit" value="I blink 3 times in 2 second intervals" />
</form>
<div id="myDiv">this is my blinking div! I blink 4 times in half second intervals</div>
<ol>
    <li>This is my infinite blinking list item</li>
    <li>I don't blink</li>
    <li>Me either</li>
    <li>Nope, not me</li>
    <ol>

CSS

.blink {
    color: black !important;
    background: yellow;
    !important;
}

JavaScript

$(document).ready(function () {

    //call the blink function on the element you want to blink
    blink("#myDiv", 4, 500); //blink a div with the ID of myDiv
    blink("input[type='submit']", 3, 1000); //blink a submit button
    blink("ol > li:first", -1, 100); //blink the first element in an ordered list (infinite times)
    blink(".myClass", 25, 5000); //blink anything that has a myClass on it
});

/**
 * Purpose: blink a page element
 * Preconditions: the element you want to apply the blink to, the number of times to blink the element (or -1 for infinite times), the speed of the blink
 **/
function blink(elem, times, speed) {
    if (times > 0 || times < 0) {
        if ($(elem).hasClass("blink")) 
            $(elem).removeClass("blink");
        else
            $(elem).addClass("blink");
    }

    clearTimeout(function () {
        blink(elem, times, speed);
    });

    if (times > 0 || times < 0) {
        setTimeout(function () {
            blink(elem, times, speed);
        }, speed);
        times -= .5;
    }
}