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);
}
First time (on refresh) the message (msg) remain on page, then when flash() run again, works good. I think, when _id exist .remove() it's working, but when is create the the message it's still on screen. What I'm doing wrong? Thanks.
You've basically answered your own question:
I think, when _id exist .remove() it's working, but when is create the the message it's still on screen
If you look at your code, the variable _id only exists when the message is onscreen already. In the case you create it, that variable does not point to 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 element already on page: http://jsfiddle.net/GyUhB/
Example with no element on page: http://jsfiddle.net/GyUhB/1/
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