Hassan Sardar
Hassan Sardar

Reputation: 4523

Automatically fadeOut Div when its visible

I have a Div which will appear when there is a session, else it will remain hidden.

What I want is to Automatically and Slowly fadeout that Div after some seconds when it becomes visible.

Here is my Code and what I have tried so far:

<?php if(isset($_SESSION['message'])){ ?>
   <div class="message">
    <?php echo $_SESSION['message']; ?>
   </div>
<?php unset($_SESSION['message']); } ?>

The Jquery:

<script type="text/javascript">
if( $('.message').is(':visible') ) {

  $(".message").fadeOut(1000);

}
</script>

The problem I am facing is that DIV appears but it doesn't Fadeout or disappear automatically. Plus there are no Errors in Console.

Upvotes: 0

Views: 1262

Answers (2)

ahren
ahren

Reputation: 16961

You don't need a timeout, or an interval. Or even to run a check to see if the element exists or is visible.

You do need to run this code when your document is ready though or at the very least, after the .message element.

$(document).ready(function(){
  $('.message').delay(5000).fadeOut(300);
});

If there is no .message element, it won't have any negative effects.

Upvotes: 2

nrsharma
nrsharma

Reputation: 2562

The problem is your code is not working as it is executing only once when the DOM is ready. You need to check value in a regular interval basis. So here you need to do something like this

You can also do this by setTimeout function

setTimeout(function(){
    if( $('.message').is(':visible') ) 
      $(".message").fadeOut(1000);
},100);

Or as I said above to execute the code you have to put it in $(document).ready function (when the DOM is ready)

$(document).ready(function () {
 if( $('.message').is(':visible') ) 
    $(".message").fadeOut(1000);
});

Upvotes: 1

Related Questions