Show the div when the variable is set and let it disappear after x seconds

I have a php page with a variable that is set to true or false for pageload. I want to show a specific div when the variable is true and then the div disappears after x seconds. When its false, the div remains hidden.

My code shows the div, but it doesn't disappear after x seconds.

    if($showNotification == TRUE){
        echo "<div class='notification'>notification!!</div>";
        echo '<script type="text/javascript">
                 $(document).load(
                    function() {
                       $("div.notification").fadeIn();
                       setTimeout(function() {
                          $("div.notification").fadeOut("slow");
                       }, 3000); 
                  });  
              </script>';

     }

      

+3


source to share


4 answers


Replace JS with the following:

$(function() {
    $('div.notification').hide().fadeIn().delay(3000).fadeOut('slow');
});  

      



Demo: http://jsfiddle.net/nEsg9/

+6


source


Instead of using:

$(document).load( ...

      



using

$(document).ready( ...

      

+1


source


if($showNotification == TRUE){
    echo "<div class='notification' style='display:none'>notification!!</div>";
    echo '<script type="text/javascript">
             $(document).load(
                function() {
                   $("div.notification").fadeIn();
                   setTimeout(function() {
                      $("div.notification").fadeOut("slow");
                   }, 3000); 
              });  
          </script>';

 }

      

This shows that it is not hidden until you fadein. Therefore fadein has no effect (it already exists).

+1


source


Use ready instead of download.

Here is a working example, but not fading out because it always displays

http://jsfiddle.net/2JKxr/1/

$(document).ready(
            function() {
               $("div.notification").fadeIn();
               setTimeout(function() {
                  $("div.notification").fadeOut("slow");
               }, 3000); 
          }); 

      

+1


source







All Articles