Search code examples
jquerysettimeoutfade

How to fadeout an element after a few second only when it is visible with jquery


Am trying to Fadeout an element after a few seconds with the following code

if(jQuery('.invalidcontent_wrapper').is(':visible')){
     var xSeconds = 4000; 
     setTimeout(function() {
     jQuery('.invalidcontent_wrapper').fadeOut('fast');
  }, xSeconds);
 };

But it has a one bug when clicking to the next time and when its opened up it hides quickly.How I can clear somehow the seconds and do this action only that time when the element is shown?


Solution

  • Try to clear the timeout when user is clicking again,

    var xSeconds = 4000; 
    var timeOut = 0;
    
    jQuery("#someClick").click(function(){
      var elem = jQuery('.invalidcontent_wrapper');
      if(elem.is(':visible')){
       clearTimeout(timeOut);
       timeOut = setTimeout(function() {
         elem.fadeOut('fast');
       }, xSeconds);
      }
    });