I got JS
as below. I want all bootstrap
alerts
to dissaper after 1 sec. It works just one time
but when i add more alerts they stays as they are. What is the cause of that?
$(document).ready(function () {
function flashh(message, category) {
if (category == "error") {
var icon = "icon-exclamation-sign";
category = "danger";
} else if (category == "success") var icon = "icon-ok-sign";
else var icon = "icon-info-sign";
$(
'<div ><i ></i> <a data-dismiss="alert">×</a>'
message
"</div>"
).prependTo("#putFlashMsg");
}
});
setTimeout:
$(document).ready(function () {
window.setTimeout(function () {
$(".alert")
.fadeTo(1000, 0)
.slideUp(1000, function () {
$(this).remove();
});
}, 5000);
});
CodePudding user response:
That's because setTimeout
is only called once. If you want to have multiple calls, use setInterval
, that is used exactly the same way but is called until clearTimeout
stops it.
CodePudding user response:
setTimeout only runs once, what you are looking for is setInterval which runs until stopped every n seconds.
$(document).ready(function () {
window.setInterval(function () {
$(".alert")
.fadeTo(1000, 0)
.slideUp(1000, function () {
$(this).remove();
});
}, 5000);
});
CodePudding user response:
Whenever you add an alert you should also create a new setTimeout
; setTimeout
should be in the "flashh" function.
function flashh(message, category) {
if (category == "error") {
var icon = "icon-exclamation-sign";
category = "danger";
} else if (category == "success") var icon = "icon-ok-sign";
else var icon = "icon-info-sign";
var alert = $(
'<div ><i ></i> <a data-dismiss="alert">×</a>'
message
"</div>"
)
window.setTimeout(function () {
alert
.fadeTo(1000, 0)
.slideUp(1000, function () {
$(this).remove();
});
}, 5000);
alert.prependTo("#putFlashMsg");
}