Thursday, June 26, 2014

How to make Alerts fade in and fade out with Bootstrap 3.0

I wanted to make the alerts work a little nicer by using fade in and fade out. I know there are classes in the CSS to handle the fade in, but they don't work in all browsers. So I wanted to implement some Javascript to make it work

Create a div for your alerts

<div id="alerts">


We need to create unique Ids, I have used this function to do so

   function createUUID() {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";

        var uuid = s.join("");
        return uuid;

Make a function to show the alert, by adding it dynamically

    function addAlert(message) {
        var id = createUUID();
        var JQueryId = "#" + id;


        window.setTimeout(function () {

            // closing the popup
            $(JQueryId).fadeTo(300, 0.5).slideUp(2000, function () {

        }, 10000);

Notice that when adding the alert, it is hidden. The JQuery fadeIn API will create the fade effect when the alert is showing. Using setTimeout, we start fading out, and then closing the alert. You can play with the numbers to have the effect you want, but this seems to work nice and make alerts popup nice, and close on their own

Testing the Alerts

    $(document).ready(function () {


        window.setTimeout(function () {
        }, 1000);

        window.setTimeout(function () {
        }, 10000);

        window.setTimeout(function () {
        }, 20000);

        window.setTimeout(function () {
        }, 20000);


The code

You can see the code and the full effect here


lee woo said...

Smiling always with a never fading serenity of countenance, and flourishing in an immortal youth. See the link below for more info.


sarah lee said...

I really enjoyed reading your article. I found this as an informative and interesting post, so i think it is very useful and knowledgeable. I would like to thank you for the effort you have made in writing this article.