Juri Strumpflohner
Juri Strumpflohner Juri is a full stack developer and tech lead with a special passion for the web and frontend development. He creates online videos for Egghead.io, writes articles on his blog and for tech magazines, speaks at conferences and holds training workshops. Juri is also a recognized Google Developer Expert in Web Technologies

HowTo: Fade out div after some seconds using jQuery

2 min read

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

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
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.

Questions? Thoughts? Hit me up on Twitter
comments powered by Disqus