Creating a Flashing Text Effect with jQuery

Sometimes you need a nice effect to boost your website’s look and feel, and catch your visitors’ attention. There are many free and ready-to-use plugins out there that can enhance the style of your website. This tutorial will guide you through the development of a cross-browser jQuery plugin that creates randomly placed, randomly sized, flashing text inside a given box. It’ll also take into account disability issues (hey, we’re talking about flashing text), providing a stop() method to stop the effect. The plugin will allow several animations on the same page, with every animation being completely independent from the others. The final result will be a JavaScript file which you can easily include in your pages.

To create the plugin, I’ll follow the jQuery plugin suggested guidelines, so it’ll be developed using jQuery plugin best practices. I’ve already made an overview on this subject in my article Implementing a Cross-Browser Context Menu as a jQuery Plugin. Also note that from now on, I’ll refer to the plugin as “Audero Flashing Text”.

Getting Started

Now that I showed you the starting point of “Audero Flashing Text”, you need to know the methods that will comprise it. It isn’t really hard to imagine that you need one to initialize the plugin and one to start the effect. The initialization function will take advantage of some default values that will be used if a specific value isn’t set. Moreover, as stated in the previous section, it would be nice to provide your users the ability to stop the effect. Last, but not least, it may be useful to have a method to test if the effect is running. Therefore, the plugin will contain the following:

  • default settings
  • init() method
  • start() method
  • stop() method
  • isRunning() method

The default settings

It’s always useful to have some default configuration if some of them aren’t specified by the user. The principal property of “Audero Flashing Text” is the set of text to show that you can specify using an array. Because we’ll have a flashing text, the actions the text will perform are: 1. slowly becoming visible, 2. remaining visible for some time, and 3. slowly disappearing. Based on this behavior, other useful settings are a fade-in, a duration, and a fade-out time. The last setting we’ll add is selection that will enable the user to choose the order of text selection. The possible values for selection are random, ascending, and descending. Translating all these words into code result in the following.

var defaultValues = {
  strings: [], // Array of strings to show
  fadeIn: 300, // Time in milliseconds
  duration: 500, // Time in milliseconds
  fadeOut: 300, // Time in milliseconds
  selection: "random" // The order of selection of the text.
                      //Possible values: "random", "ascending", "descending"
};

The init() method

We’ll use the init() method to test how the plugin has been called, and to setup the style of the box where we’ll run the effect. It accepts just one parameter, an object containing at least an array of strings to show, but also the values that will overwrite the default ones. Alternatively, the function can be called without parameters, and in this case the default values apply. In this case, the set of strings to display will use the text of the children nodes of the selected element. The latter way allows you to start experimenting with the plugin right away. After the tests, the init() method will hide the children of the selected element using the visibility CSS property, so the height of the box won’t be reduced. At this point the last thing to do is call the start() function to run the animation. The code for init() is shown below.

init: function(options)
{
  if (typeof options === "undefined" || options === null) {
    options = {};
  }
  if (typeof options.strings === "undefined" || options.strings == null) {
    if (this.children().size() === 0) {
      $.error("If you don't specify the texts to show, the element must have at least a child");
      return;
    }
    else {
      options.strings = this.children().map(function() {
        return $(this).text();
      });
    }
  }

  this.css("position", "relative");
  this.children().css("visibility", "hidden");

  methods.start($.extend({}, defaultValues, options), null, this.attr("id"));
}

The start() method

This is the most important part of the plugin because it holds the code that actually runs the effect. It accepts the following three parameters.

  • settings – the configuration object.
  • index – the string to be displayed.
  • idElem – the id of the box where the effect applies.

Just like the init() method, it starts by testing the parameters. Afterwards, it creates a <span> element that will float on the specified box. When it’s created, the element is invisible (display: none), so it can slowly appear using the fade methods. As you’ll see in a few moments, the fadeOut() function has a callback that will remove the created element from the DOM, and then run again the effect with the next, previous, or random strings based on the current configuration. The last lines of the method set the position so the element will fit the box’s size.

start: function(settings, index, idElem)
{
  if (typeof idElem === "undefined") {
    idElem = this.selector;
  }
  if (typeof settings === "undefined") {
    $.error("Invalid method call: No settings specified");
    return;
  }
  if (index == null) {
    if (settings.selection === "ascending")
      index = 0;
    else if (settings.selection === "descending")
      index = settings.strings.length - 1;
    else
      index = Math.floor(Math.random() * settings.strings.length);
  }

  var $text = $("&lt;span&gt;")
  .text(settings.strings[index])
  .addClass("audero-flashing-text") // This is used as a bookmark to help the stop method
  .css({
    position: "absolute",
    display: "none",
    fontSize: (Math.random() * 2 + 0.5) + "em"
  })
  .appendTo("#" + idElem)
  .fadeIn(settings.fadeIn)
  .animate({opacity: 1}, settings.duration) // Simulate delay
  .fadeOut(settings.fadeOut, function() {
    // Remove the current element
    $(this).remove();
    var nextIndex;
    if (settings.selection === "ascending")
      nextIndex = (index + 1) % settings.strings.length;
    else if (settings.selection === "descending")
      nextIndex = (index === 0) ? settings.strings.length : index - 1;
    else
      nextIndex = Math.floor(Math.random() * settings.strings.length);
    // Start again the effect
    methods.start(settings, nextIndex, idElem);
  });
  // Set the position so the element will fit the box's size
  var posX = Math.floor(Math.random() * ($("#" + idElem).width() - $text.outerWidth()));
  var posY = Math.floor(Math.random() * ($("#" + idElem).height() - $text.outerHeight()));
  // Set the position of the text
  $text.css({
    left: posX + "px",
    top: posY + "px"
  });
}

The stop() method

The stop() method is used to stop the animation, remove the last <span> elements created from the DOM, and then restore the normal visibility properties. As you can see looking at the source below, the text is removed smoothly. The method first stops the animation (jQuery stop() method), then fades out the text so it slowly disappears from the screen (jQuery fadeOut() method), and then removes it from the DOM (jQuery remove() method).

stop: function()
{
  this.css("position", "inherit");
  // Removes the floating text
  this
  .children("span.audero-flashing-text")
  .stop(true)
  .fadeOut(defaultValues.fadeOut)
  .remove();
  // Restore the default visibility
  this.children().css("visibility", "visible");
}

The isRunning() method

This method is very easy to understand because it simply tests if the given element is running the flashing effect. The testing process checks for <span> elements of class audero-flashing-text. The method returns true if at least one element is found, and false otherwise. The code explained is listed below.

isRunning: function()
{
  return (this.children("span.audero-flashing-text").size() > 0);
}

How to use the plugin

Now that you’ve seen all the methods, it’s time to see a couple of examples. Assume that you have the following <div>.

<div id="box">
  <p>Lorem>/p>
  <p>Ipsum>/p>
  <p>Dolor</p>
  <p>Sit</p>
  <p>Amet</p>
</div>

To run the effect using the text of the paragraphs, all you have to do is this:

$("#box").auderoFlashingText();

The following is an example that uses the same markup seen before but with different settings:

$("#box").auderoFlashingText({
  fadeOut: 1500,
  selection: "ascending"
});

Conclusions

This article has shown you how to create a jQuery plugin that creates a flashing text effect on a given box. To see how it works, download the source code and take a look at the documentation included in the repository. The Audero Flashing Text plugin is completely free. You can also change it or improve it further since it’s dual licensed under MIT and GPL-3.0

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Adam Košinar

    This is great site, but what I miss almost every time here, is a live demo. I have to go throught the code to see what it actually is…

  • yasin

    Thank you very much. I think it would be great if there is some kind of DEMO without/before downloading stuff

  • DD

    Just because one has the ability to do something does not mean it’s a good idea in the first place. Blinking text is one of those things. The tag was removed from the W3C recommendations because it was just so damn annoying. It smacked of amateurism, self promotion (Look at me! Look at me!) not to mention that pesky issue of possibly triggering photo-sensitivity issues (epileptic seizures) in some people. Sorry but updating the technology does not correct the problem. Even providing a user ability to stop it doesn’t offer a pass to acceptance. Ensuring accessibility is the responsibility of the creator. In other words, do no harm.

  • pete

    Why write a long tutorial to recreate the tag?!

    • pete

      oops, tag didn’t appear – meant to say blink tag