Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout() and remove() doesn't work as expected

Tags:

jquery

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.

like image 636
user2039290 Avatar asked Jun 05 '26 05:06

user2039290


1 Answers

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/

like image 116
Jamiec Avatar answered Jun 06 '26 22:06

Jamiec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!