I have following code to auto-close Bootstrap alert after 5 seconds
$(".alert").alert();
window.setTimeout(function() { $(".alert").alert('close'); }, 5000);
When closing alert, content jumps top not very smoothly. Is it somehow possible to get content slide smoothly into place?
EDIT: Now the code is working correctly when I'm testing it on JSFiddle, but when I'm using it on my server, only half of it works. The alert is fading out after 3 seconds, but if I press Close button, nothing happens.
Following is my code. Maybe the problem is PHP echo, because the code is exactly the same as on JSFiddle.
echo "<div class=\"alert alert-success\" role=\"alert\">".$message."<button type=\"button\" class=\"close\"><span aria-hidden=\"true\">×</span></button></div>";
As per the bootstrap doc (http://getbootstrap.com/javascript/#alerts):
To have your alerts use animation when closing, make sure they have the
.fade
and.in
classes already applied to them.
This will cause the alert to fade out.
However, as I see this animates the opacity but does not animate the height and hence the abrupt jump of the content when the alert is removed.
In this case you do not use the default functionality, but do the animation yourself on some event (setTimeout delay in your case). By animating the height of the alert, the content which follows will automatically appear to be animating.
Easiest would be to use the jQuery .slideUp
:
Example:
window.setTimeout(function() {
//$(".custom-alert").alert('close'); <--- Do not use this
$(".custom-alert").slideUp(500, function() {
$(this).remove();
});
}, 3000);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="alert alert-warning custom-alert" role="alert">
<strong>Warning!</strong> This alert will animate itself to close in 3 secs.
</div>
<p>Lorem Ipsum</p>
<p>Lorem Ipsum</p>
<p>Lorem Ipsum</p>
Edit: (based on Op comment)
If you want that to happen on close button click and also the fade and slide animations to be separate, the concept remains the same. Just call the routine on close button click and stagger or chain the animations.
Quick Demo:
$("div.alert").on("click", "button.close", function() {
$(this).parent().animate({opacity: 0}, 500).hide('slow');
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br><hr>
<div class="alert alert-warning" role="alert">
<button type="button" class="close">
<span>×</span>
</button>
<strong>Warning!</strong> This alert will animate on clicking the close button.
</div>
<p>Lorem Ipsum</p>
<p>Lorem Ipsum</p>
<p>Lorem Ipsum</p>
Combined Fiddle: http://jsfiddle.net/abhitalks/e3k5jnyw/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With