Often developers want to pull focus to a specific area of the screen—a menu item, a contact card, a forum post, really any block of information that needs to temporarily stand out.

A real-world example is the quick blink of the background of a post on StackOverflow. Check out this post, and look for the fade-out effect; it’s there to tell you, “Hey, this is the post you want”.

There are a few ways to take advantage of this usability effect. An easy way is with CSS transitions, which have been available since Chrome 1, FireFox 4, and IE10.

The transition feature in the transitions spec of CSS3 gives developers a way to add an animation effect to an element when some property of that element changes.

What properties can be animated? A short list of the more useful transition-supported properties are listed below: (full list)

  • color
  • opacity
  • background-color
  • border-radius
  • margin / padding
  • width / height

For our flash, we’ll be targeting the background-color property to quickly change and revert the background color of a DOM element.

First, we build our element:

<div id="heyListen" class="flashable">
  Hey, Listen!
</div>

Now we need two CSS styles. One for the base state of our element (.flashable), and one to engage the flash animation (.flash):

/* default state */
.flashable {
  border: 1px solid #ddd;
  width: 250px;
  height: 75px;
  text-align: center;
  background-color: #f0f0f0;
  transition: background-color 0.5s linear;
}

/* flashing state */
.flash {
  background-color: #feb439;
}

Let’s pick apart the transition rule:

transition: background-color 0.5s linear;

We are telling the browser to take 0.5 seconds to change the background-color of the element in a linear fashion. linear is a timing function—check out this article for a complete listing. Other popular timing functions include ease-in and ease-out.

With these classes, we have the power to make an element “flash” by appending the .flash class onto an element and subsequently removing it. When .flash is added to an element, it will take 0.5 seconds to fade the background from #f0f0f0 to #feb439. When .flash is removed, it will take another 0.5 seconds to fade from #feb439 back to #f0f0f0. The result is a flash effect that lasts for 1 second.

To add and remove the class, we’ll use jQuery for simplicity. It can easily be done in vanilla JavaScript, but jQuery leads to a much less verbose response.

var flash = function (id) {
  $(id).addClass('.flash');

  setTimeout(function () {
    $(id).removeClass('.flash');
  }, 500);
};

If you want a faster flashing animation, just mess around with the time in the transition rule, and make sure it equals the delay parameter in the setTimeout function.