Flashbags done right

Introduction

We would like to create a simple solution for Flashbags (short messages what appears after some action and disappears after some fixed time). We will be using Bootstrap as the base CSS framework to make things easier.

The problem

Our flashbags will display different messages - some of them will only show you if the payment went well (e.g. "Payment successful") and others some more complicated and longer messages (e.g. "Your payment has been rejected due to exceeded Credit Card expiration date. Please try again with another Credit Card"). The first message can be shown for for example 1-2 seconds but the second one can be little hard to read for some (you lose some time before you find the Flashbag, then you have to locate the text and start reading). In some cases people need to read twice to understand what the message was about.

Solution

HTML code:

<div class="flashbags">
  <div class="alert alert-danger alert flashbag">
    <span class="message-text">
      Payment unsuccessful
    </span>
  </div>
  <div class="alert alert-warning alert flashbag">
    <span class="message-text">
      Your payment has been rejected due to exceeded
      Credit Card expiration date. Please try again
      with another Credit Card
    </span>
  </div>
</div> 

CSS Code:

.flashbags {
    position: absolute;
    width: 90%;
    left: 50%;
    top: 30px;
}

.flashbag {
    position: relative;
    left: -50%;
}

And the main magician, JS Code:

var letterFactor = 70;
var delayBuffer = 2000;

$('.flashbag').each(function () {
  var lettersCount = $(this).find('.message-text').text().length;

  $(this)
    .delay(lettersCount * letterFactor + delayBuffer)
    .fadeOut(700);
});

As you can see the simple method is enchanted with letterFactor (timeout factor for one letter) and delayBuffer which is the mininum timeout before the flashbag fades out.

The full solution can be found in this JS Fiddle

Click RESULT on the left top corner to play again.

Of course we should use a fade class from Bootstrap - that is a recommended way to do it. For the sake of this article I have used fadeOut to visualise what is happending after the delay.

If you need a ready-to-use jQuery library you can find it here, in my repo.