Bootstrap 3 - How to fade-in alert box on-click and fade-out after 3 seconds

35,301

Solution 1

I use something like this. (The animation looks very pretty!). Simply add this JS, and apply the class flash to every item you want to disappear. MAKE SURE YOU ALSO ADD THE fade-in CLASS TO EVERYTHING! The fade-in class comes with bootstrap. It will fade out in 5 seconds.

window.setTimeout(function() {
  $(".flash").fadeTo(500, 0).slideUp(500, function(){
      $(this).remove();
  });
}, 5000);

Solution 2

Try something like this

.fade {
  opacity: 0;
  -webkit-transition: opacity 0.15s linear;
  -moz-transition: opacity 0.15s linear;
  -o-transition: opacity 0.15s linear;
  transition: opacity 0.15s linear;
}
.fade.in {
  opacity: 1;
  -webkit-transition: opacity 3.0s linear;
  -moz-transition: opacity 3.0s linear;
  -o-transition: opacity 3.0s linear;
  transition: opacity 3.0s linear;
}

You need to put the fade and fade.in property onto your alert box and alert box hide though. - But just set the transition times for both to match what you need. Basically what you are doing here is setting the opacity, then the length of time it is taking to do this. The reason we have 4 different values all with different times are to make it cross browser compatible.

Share:
35,301
user3314402
Author by

user3314402

Updated on July 28, 2022

Comments

  • user3314402
    user3314402 almost 2 years

    I am using AngularJS and Bootstrap 3. My web app has an "Update" button where it saves any changes the user makes. When the user clicks on the "Update" button, I want to activate and fade-in bootstrap's alert box saying "Information has been saved" and then fade-out after 3 seconds. I don't know how to create this function and may need some help..

    UPDATE:

    I have decided to use this approach:

    HTML

    <button type="button" class="btn btn-info" ng-click="save()">Update</button>
    
    <div id = "alert_placeholder"></div>
    

    JavaScript

    $scope.save = function() {
        $('#alert_placeholder').html('<div class="alert alert-warning alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><span>Your information has been updated.</span></div>')
        setTimeout(function() {
            $("div.alert").remove();
        }, 3000);
    }
    

    I would like to make the alert box fade-in when it first appears and fade-out as it gets removed after 3 seconds, but I am not sure how to make it work with the code I have.