206

My need is to call alert when I click on Add to Wishlist button and should disappear the alert in 2 secs. This is how I tried, but the alert is disappearing instantly as soon as it is appearing. Not sure, where the bug is.. Can anyone help me out?

JS Script

$(document).ready (function(){
   $("#success-alert").hide();
   $("#myWish").click(function showAlert() {
      $("#success-alert").alert();
      window.setTimeout(function () { 
         $("#success-alert").alert('close'); 
      }, 2000);             
   });      
});

HTML Code:

<div class="product-options">
   <a id="myWish" href="" class="btn btn-mini">Add to Wishlist </a>
   <a href="#" class="btn btn-mini"> Purchase </a>
</div>

Alert Box:

<div class="alert alert-success" id="success-alert">
   <button type="button" class="close" data-dismiss="alert">x</button>
   <strong>Success!</strong>
   Product have added to your wishlist.
</div>
srikanth_naalla
  • 2,305
  • 2
  • 17
  • 23
  • 1
    possible duplicate of http://stackoverflow.com/questions/16604407/jquery-remove-bootstrap-alert-after-certain-amount-of-time and http://stackoverflow.com/questions/7643308/how-to-automatically-close-alerts-using-twitter-bootstrap – 4dgaurav Apr 16 '14 at 06:49

13 Answers13

334

For a smooth slide-up:-

$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
    $("#success-alert").slideUp(500);
});

$(document).ready(function() {
  $("#success-alert").hide();
  $("#myWish").click(function showAlert() {
    $("#success-alert").fadeTo(2000, 500).slideUp(500, function() {
      $("#success-alert").slideUp(500);
    });
  });
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<div class="product-options">
  <a id="myWish" href="javascript:;" class="btn btn-mini">Add to Wishlist </a>
  <a href="" class="btn btn-mini"> Purchase </a>
</div>
<div class="alert alert-success" id="success-alert">
  <button type="button" class="close" data-dismiss="alert">x</button>
  <strong>Success! </strong> Product have added to your wishlist.
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
Saad
  • 3,340
  • 2
  • 10
  • 32
AyB
  • 11,609
  • 4
  • 32
  • 47
  • 3
    It's not working second time you clicked the button. Because of alert('close') If you use slideUp() it's working @ICanHasKittenz – Fatih Alp Aug 02 '16 at 19:32
  • 1
    Works beautiful, but what's this line $("#success-alert").alert(); usage? I've removed it and works too. – Roberto Sepúlveda Bravo Jun 17 '17 at 05:34
  • 1
    @RobertoSepúlvedaBravo it's to give the close functionality to the alert box but you are right, it's not needed here because we are using the `data-dimiss="alert" ` attribute. Will update the script. – AyB Jun 18 '17 at 05:10
  • Did not work for me. The other below here examples worked fine, however. – Terje Nesthus Sep 21 '17 at 03:54
  • @TerjeNesthus Can you explain what exactly didn't work? The alert is not sliding up? Or it's not working the second time? Can I know the version of your bootstrap? This was meant to be for Bootstrap 3 and I haven't tested them on the later versions. – AyB Sep 24 '17 at 07:45
  • Why inside callback there is slideUp again? It works from me this way: $('.alert-success').fadeTo(2000, 500).slideUp(1000); – Dariux Jan 05 '18 at 18:43
  • What's nice about this solution is that you can set the class of your alert to `.hidden` then remove that class before triggering the `.fadeTo()` the the `.slideUp()` function then takes care of everything else. Thanks. – DazBaldwin Apr 12 '18 at 08:14
  • Good solution. I think replacing `#success-alert` with `.alert` is much more practical though as it covers any alert that pops up. i.e. `warning`, `info`, `success`, etc. – Jake Apr 08 '19 at 22:21
  • For those of us, who try to avoid jQuery, there are simple [animation functions](https://gist.github.com/skttl/b8ea597ebf2db66a3e2a06491f7b4029) available throughout the internetz. – s3c Feb 09 '21 at 13:28
  • it is too fast to look at, isnt it? – Muhammad Ali Aug 29 '21 at 08:08
73

Using a fadeTo() that is fading to an opacity of 500 in 2 seconds in "I Can Has Kittenz"'s code isn't readable to me. I think it's better using other options like a delay()

$(".alert").delay(4000).slideUp(200, function() {
    $(this).alert('close');
});
gabe
  • 1,873
  • 2
  • 20
  • 36
Alex Fuentes
  • 61
  • 2
  • 5
71

Why all the other answers use slideUp is just beyond me. As I'm using the fade and in classes to have the alert fade away when closed (or after timeout), I don't want it to "slide up" and conflict with that.

Besides the slideUp method didn't even work. The alert itself didn't show at all. Here's what worked perfectly for me:

$(document).ready(function() {
    // show the alert
    setTimeout(function() {
        $(".alert").alert('close');
    }, 2000);
});
ADTC
  • 8,999
  • 5
  • 68
  • 93
25

I found this to be a better solution

$(".alert-dismissible").fadeTo(2000, 500).slideUp(500, function(){
    $(".alert-dismissible").alert('close');
});
Björn
  • 5,696
  • 1
  • 24
  • 34
Jaimie
  • 361
  • 3
  • 2
24

one more solution for this Automatically close or fade away the bootstrap alert message after 5 seconds:

This is the HTML code used to display the message:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<div class="alert alert-danger">
This is an example message...
</div>


<script type="text/javascript">

$(document).ready(function () {
 
window.setTimeout(function() {
    $(".alert").fadeTo(1000, 0).slideUp(1000, function(){
        $(this).remove(); 
    });
}, 5000);
 
});
</script>

It's not limited to showing the message through JS, the message could already be displayed when the page loads.

Divyesh Kanzariya
  • 3,629
  • 3
  • 43
  • 44
11

I know this thread is old, but I just thought I would add my script for Bootstrap 5, incase anyone else needs it

<script>
    setTimeout(function() {
        bootstrap.Alert.getOrCreateInstance(document.querySelector(".alert")).close();
    }, 3000)
</script>
lonny
  • 135
  • 1
  • 4
4

Html:

<div class="alert alert-info alert-dismissible fade show js-alert" role="alert">

Javascript:

  if (document.querySelector('.js-alert')) {
    document.querySelectorAll('.js-alert').forEach(function($el) {
      setTimeout(() => {
        $el.classList.remove('show');
      }, 2000);
    });
  }
Gigoland
  • 1,287
  • 13
  • 10
3
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
    $("#success-alert").alert('close');
});

Where fadeTo parameters are fadeTo(speed, opacity)

Community
  • 1
  • 1
Marwah Abdelaal
  • 111
  • 2
  • 10
2

This is a good approach to show animation in and out using jQuery

  $(document).ready(function() {
      // show the alert
      $(".alert").first().hide().slideDown(500).delay(4000).slideUp(500, function () {
         $(this).remove(); 
      });
  });
yehanny
  • 81
  • 1
  • 4
1

Tiggers automatically and manually when needed

$(function () {
    TriggerAlertClose();
});

function TriggerAlertClose() {
    window.setTimeout(function () {
        $(".alert").fadeTo(1000, 0).slideUp(1000, function () {
            $(this).remove();
        });
    }, 5000);
}
Arun Prasad E S
  • 9,489
  • 8
  • 74
  • 87
1

C# Controller:

var result = await _roleManager.CreateAsync(identityRole);
   if (result.Succeeded == true)
       TempData["roleCreateAlert"] = "Added record successfully";

Razor Page:

@if (TempData["roleCreateAlert"] != null)
{
    <div class="alert alert-success">
        <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
        <p>@TempData["roleCreateAlert"]</p>
    </div>
}

Any Alert Auto Close:

<script type="text/javascript">
    $(".alert").delay(5000).slideUp(200, function () {
        $(this).alert('close');
    });
</script>
1

Based on @Ionny answer I am using this in Bootstrap 5 to dismiss several alert messages (validation errors). I am using the CSS class alert-flash to only target certain alert blocks.

/**
 * Auto hide the flash alerts after a few seconds
 */
setTimeout(function() {
    var alertList = document.querySelectorAll('.alert-flash');
    alertList.forEach(function (alertNode) {
        bootstrap.Alert.getOrCreateInstance(alertNode).close(); 
    })
}, 3000)

cdsaenz
  • 520
  • 1
  • 10
  • 15
0

This worked perfectly even though you clicked the button multiple times. Here I created an onClick function to trigger the closeAlert function.

function closeAlert(){
    const alert = document.getElementById('myalert')
    alert.style.display = "block"

    setTimeout(function(){ 
        alert.style.display = "none"

    }, 3000);

 }