Reputation: 20415
I have an alert-message element, which I would like to hide after 2 seconds. I have a javascript that runs after the page load, and it does hire any alerts appears when the page load.
However, there are alerts that shows up after the page load, and these alerts will stay on. How do I observe changes, i.e., if the alert-message element is visible again, to hide it after 2 seconds?
This the code I used to hide the first alert:
$(document).ready( function(){
var hide_delay = 4000; // starting timeout before first message is hidden
var hide_next = 800; // time in mS to wait before hiding next message
$(".alert-message").slideDown().each( function(index,el) {
window.setTimeout( function(){
$(el).slideUp(); // hide the message
}, hide_delay + hide_next*index);
});
Thank you.
Upvotes: 0
Views: 367
Reputation: 8234
Here's a Fiddle idea: http://jsfiddle.net/ekr8v/4/
When you create an alert, you give it an ID and you create a timeout (see Eli Sand's code above) that will remove that ID after 2 seconds.
In the tutorial in my fiddle, I just used the Unix timestamp which I think would work just fine here.
Upvotes: 1
Reputation: 4611
I think you want something like the "DOMNodeInserted" event but this is not supported in IE. So you can use liveQuery to listen to DOM changes instead. Hopefully this is something that you're looking for.
You can then use it like this to listen to element changes:
$('#elementToListenTo').livequery(function(){
// If $(this) element has been changed, perform things below.
var timeout = window.setTimeout(function(){
// Perform a task after 2 seconds
$(".alert-message").slideDown();
},2000);
});
Upvotes: 1
Reputation: 1032
It sounds to me like you might want a timer? What you would want to do is, at the end of the function/code that displays the alert to the user, do something like this:
var timer = window.setTimeout(function() {
// code here to hide the alert
}, 2000);
The number 2000 is in milliseconds and should mean that at roughly 2 seconds after the timer is created, the code would run in the anonymous function that would then hide the alert.
Upvotes: 2