lang="en-US"> jQuery Tutorial: Blinking Elements – continously or a specific number of times –  Design1online.com, LLC

jQuery Tutorial: Blinking Elements – continously or a specific number of times

This tutorial will show you how to create a blinking effect on any page element: divs, ordered list items, inputs, buttons, you name it.

1. Create A Stylesheet

First create a stylesheet called blink.css and define a blink class that will give your element a “blinking” effect. For this tutorial I’ve chosen a pink color with white text.

.blink {
     color: #FFF !important;
     background: #FC79CE; !important;
}

2. Write the jQuery

Now let’s create a javascript file called jquery.blink.js. Inside this file we’re going to do the following:

$(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;
     }
}

3. Putting It Together

Now we create our html page, include our javascript and css file and watch our jQuery work it’s magic.

<link rel="stylesheet" href="blink.css" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="jquery.blink.js" /></script>
    <form method="post">
        <p>Blink 25 times in 5 second intervals: <input type="text" name="username" /></p>
        <p>I will do the same: <textarea></textarea></p>
        <p><span>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 met</li>
    <ol>

4. Demo and Download Code

Try the JSFiddle Demo | Download the Working Code

You may also like...

3 Responses

  1. ffgfg says:

    thank u

  2. Ronit says:

    very very nice! good work bro..

  3. Gaurav says:

    That’s very intelligently done 🙂

Leave a Reply