SetTimeout () and remove () not working as expected
I have this function:
function flash(msg) {
var _id = $('#flash_notice__');
if( _id.length > 0 ) {
_id.html(msg);
} else {
$('<div id="flash_notice__">'+ msg +'</div>').appendTo('body');
//$('body').append('<div id="flash_notice__">'+ msg +'</div>');
}
setTimeout(function(){
_id.fadeOut(500, function(){
$(this).remove(); //or _id.remove();
});
}, 2500);
}
The first time (on refresh) the message (msg) stays on the page, then when flash () runs again, it works well. I think when _id exists .remove () it works, but when the message is generated it is still displayed on the screen. What am I doing wrong? Thank you.
source to share
You basically answered your own question:
I think when the _id exists .remove () it works, but when the message is generated it is still displayed on the screen
If you look at your code, the variable _id
only exists when the message is already on the screen. If created, this variable does not indicate anything:
var _id = $('#flash_notice__');
...
} else {
$('<div id="flash_notice__">'+ msg +'</div>').appendTo('body');
}
Change your code to:
function flash(msg) {
var _id = $('#flash_notice__');
if( _id.length > 0 ) {
_id.html(msg);
} else {
_id = $('<div id="flash_notice__">'+ msg +'</div>').appendTo('body');
}
setTimeout(function(){
_id.fadeOut(500, function(){
$(this).remove(); //or _id.remove();
});
}, 2500);
}
Example with an element already on the page: http://jsfiddle.net/GyUhB/
Example without an element on the page: http://jsfiddle.net/GyUhB/1/
source to share
Try:
function flash(msg) {
var _id = $('#flash_notice__');
if( !_id.length ) {
_id = $('<div id="flash_notice__">'+ msg +'</div>').appendTo('body');
} else {
_id.html(msg).show();
}
setTimeout(function(){
_id.fadeOut(500, function(){
$(this).hide();
});
}, 2500);
}
Note: .hide()
not .remove()
, so _flash_notice is available for reuse next time. Otherwise, a new _flash_notice will be created every time.
source to share