Creating a Flashing Text Effect with jQuery

Share this article

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

Frequently Asked Questions (FAQs) about Creating a Flashing Text Effect with jQuery

How can I adjust the speed of the flashing text effect in jQuery?

The speed of the flashing text effect can be adjusted by modifying the duration parameter in the .fadeIn() and .fadeOut() methods. The duration is specified in milliseconds; therefore, a lower value will speed up the effect, while a higher value will slow it down. For instance, if you want the text to flash faster, you can reduce the duration to 500 milliseconds like so: $(“#myText”).fadeIn(500).fadeOut(500);

Can I apply the flashing text effect to multiple elements at once?

Yes, you can apply the flashing text effect to multiple elements simultaneously. To do this, simply use a class selector instead of an ID selector. For example, $(“.myClass”).fadeIn().fadeOut(); will apply the effect to all elements with the class “myClass”.

Is it possible to stop the flashing text effect after a certain period?

Yes, you can stop the flashing text effect after a certain period using the setTimeout function. This function allows you to specify a delay in milliseconds after which a specified function will be executed. For example, you can stop the flashing effect after 5 seconds (5000 milliseconds) like so: setTimeout(function(){ $(“#myText”).stop(); }, 5000);

How can I make the text flash in different colors?

To make the text flash in different colors, you can use the .css() method in combination with the .fadeIn() and .fadeOut() methods. The .css() method allows you to change the CSS properties of an element. For example, you can change the color of the text to red like so: $(“#myText”).css(“color”, “red”).fadeIn().fadeOut();

Can I use the flashing text effect with other jQuery effects?

Yes, you can combine the flashing text effect with other jQuery effects to create more complex animations. For example, you can make the text slide down while it’s flashing like so: $(“#myText”).slideDown().fadeIn().fadeOut();

Is it possible to create a flashing text effect without jQuery?

Yes, it’s possible to create a flashing text effect without jQuery using CSS animations or JavaScript. However, jQuery simplifies the process and makes it easier to create complex animations with less code.

How can I make the text flash only when a user hovers over it?

You can make the text flash only when a user hovers over it by using the .hover() method. This method specifies two functions to run when the mouse pointer hovers over the selected elements. For example: $(“#myText”).hover(function(){ $(this).fadeIn().fadeOut(); });

Can I apply the flashing text effect to an element when a button is clicked?

Yes, you can apply the flashing text effect to an element when a button is clicked by using the .click() method. This method attaches an event handler function to an HTML element that is executed when the element is clicked. For example: $(“#myButton”).click(function(){ $(“#myText”).fadeIn().fadeOut(); });

How can I make the text flash in a loop?

You can make the text flash in a loop by using the .animate() method in combination with a custom function. This will create a recursive loop that will keep the text flashing until you stop it. For example: function flash() { $(“#myText”).fadeIn().fadeOut(flash); } flash();

Is the flashing text effect supported in all browsers?

The flashing text effect, as implemented with jQuery’s .fadeIn() and .fadeOut() methods, is supported in all modern browsers that support jQuery, including Chrome, Firefox, Safari, Edge, and Internet Explorer 9+. However, the effect may not work in older browsers that do not support jQuery or have JavaScript disabled.

Aurelio De RosaAurelio De Rosa
View Author

I'm a (full-stack) web and app developer with more than 5 years' experience programming for the web using HTML, CSS, Sass, JavaScript, and PHP. I'm an expert of JavaScript and HTML5 APIs but my interests include web security, accessibility, performance, and SEO. I'm also a regular writer for several networks, speaker, and author of the books jQuery in Action, third edition and Instant jQuery Selectors.

IntermediatejQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week