HowTo: Fade out div after some seconds using jQuery

Today I made a quick change to my blog. I don't know whether many of my readers noticed the possibility of expanding the reading area by clicking on the gray vertical bar which separates the left column with the post content.

Therefore, what I wanted to change was to automatically hide the left navigation bar after a certain amount of time and so to give maximum focus on the written content, which is, after all, the most important part :) .
Shouldn't be a problem with jQuery and so the first Google query brought me directly to StackOverflow (who wonders ;) ). The raised question there is exactly what I needed, I was however not really satisfied by the accepted answer. Its author suggests to use the jQuery's fadeOut method
$("#myDiv").fadeOut(5000);

This however does not cause a delay of 5 seconds but specifies the timespan of the fade-out process itself. Being not satisfied about the answer I went ahead in search of an alternative and came up with this solution, which btw is actually a workaround. What I did is to make use of the "fadeTo" method which allows takes two parameters:
  1. The speed of the process of "fading to". One can indicate milliseconds as well as semantic names like "slow".
  2. The percentage of opacity, where 1 = 100% opacity.
I specified it like
$("#sidebar-column").fadeTo(15000,1).fadeOut(1000);
So the process starts immediately and for 15 seconds it fades (an already 100% opaque container) to 100% opacity, i.e. nothing changes. This to simulate the delay. Then the fadeOut will start for a timespan of 1 second. VoilĂ . You have your delay. Now, of course you can find the "correct" solution, using other jQuery plugins which have been made just for the purpose of creating a delay (like pause(...) ?) etc.

The mentioned solution has some advantages which I'd not disregard:
  • it is a simple one-liner
  • you don't need any additional plugins
Here's my SO contribution.
Kindle

Comments

0

Your ad here?