jQuery – Animation on Visibility

Next: jQuery – Using animate() with fadeIn() or fadeOut() at the same time

We can hide and show any HTML elements by the fadeIn() and fadeOut() jQuery functions. Those elements will be set to display: none in CSS. Unlike setting visibility: hidden which the hidden element will still occupied some spaces in the rendered web page, the faded out element will disappear.

So if you want to have the fadeIn and fadeOut features while keeping the elements in the webpage, here is what you could do.

First, set the element with visibility: hidden and opacity: 0.0.

#show-me {
  visibility: hidden;
  opacity: 0.0;
}

 

Second, make the element visible when the DOM is ready.

$(document).ready(function() {
  $('#show-me').css('visibility', 'visible').animate({opacity: 1.0}, 2000);
});

 

Here is the complete example.

<html>
  <head>
    <style type="text/css">
      #show-me {
        visibility: hidden;
        opacity: 0.0;
      }
    </style>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $('#show-me').css('visibility', 'visible').animate({opacity: 1.0}, 2000);
      });
    </script>
  </head>
  <body>
    <div id="show-me">
      <a href="http://eureka.ykyuen.info">Eureka!</a>
    </div>
  </body>
</html>

 

On the other hand, if you wanna hide an element, try the following example.

<html>
  <head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $('#hide-me').animate({opacity: 0.0}, 2000, setInvisble);
      });
      
      function setInvisble() {
        $('#hide-me').css('visibility', 'hidden');
      }
    </script>
  </head>
  <body>
    <div id="hide-me">
      <a href="http://eureka.ykyuen.info">Eureka!</a>
    </div>
  </body>
</html>

 

Done =)

Reference: StackOverflow – Visibility option in jquery

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s