Reputation: 51
How to automatically hide or remove DIV's content. I have container where I put some messages.
<div id="msg-container"></div>
I'd like to show new message only for few seconds, it can be 5, 10 whatever, but then I want it empty, add new message, show it and than hide. Of course I know the "trick" with setTimeout:
setTimeout(function(){
$('#divID').remove();
}, 5000);
but in this option I have to pass this script with every message and it's not what I am looking for. I have also tried setInterval, but as the name says it's interval, so the message can be visible for 5 seconds or can be even invisible if it hits the end of the interval time.
Is there any way to write simple script that will clean my DIV exactly after 5 seconds after it was filled with content?
Upvotes: 1
Views: 5611
Reputation: 2585
One way to go is to use a combination of setTimeout
and a custom event. Everytime you want to add a new message or set of messages, you will trigger this event and pass the corresponding message/messages to it.
E.g.
$('.message').trigger('message:add', 'I am your new message!');
and then
$('.message').on('message:add', function(event, message) {
// do your thing
});
JSFiddle here
Or you can use a "growl" plugin, e.g. http://ksylvest.github.io/jquery-growl/
Upvotes: 0
Reputation: 3029
Suppose you have a message container.
<div id="message-container">
</div>
Just create something like a message manager to handle this kind of feature.
var MessageManager = {
show: function(content) {
$('#message-container').html(content);
setTimeout(function(){
$('#message-container').html('');
}, 5000);
}
};
MessageManager.show('<h1>Testing</h1>');
Every time you want to show something, just call MessageManager.show() with the content you want to show.
Upvotes: 3
Reputation: 192
First and foremost, your selector does not match the id of your div.
setTimeout(function(){
$('#msg-container').remove();
}, 5000);
However, if that was intentional and you are trying to remove divs inside of "msg-container" let us say with class "divClass", it would be like this.
setTimeout(function(){
$('#msg-container .divID').remove();
}, 5000);
Upvotes: 0