title: How to do fade-in and fade-out with JavaScript and CSS
body: <p>I want to make an HTML div tag fade in and fade out. </p>
  
  <p>I have some code that fades out, but when I fade in, the opacity of the div stays at 0.1 and doesn't increase.</p>
  
  <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
  
   &lt;html xmlns="http://www.w3.org/1999/xhtml" lang="en"&gt;
   &lt;head&gt;
      &lt;title&gt;Fade to Black&lt;/title&gt;
      &lt;script type="text/javascript"&gt;
          //&lt;![CDATA[
          function slidePanel(elementToSlide, slideSource)
          {
              var element = document.getElementById(elementToSlide);
  
              if(element.up == null || element.up == false) {
                  setTimeout("fadeOut(\"" + elementToSlide + "\")", 100);
                  element.up = true;
                  slideSource.innerHTML = "Bring it down";
              } else {
                  setTimeout("fadeIn(\"" + elementToSlide + "\")", 100);
                  element.up = false;
                  slideSource.innerHTML = "Take it up";
              }
          }
  
          function fadeIn(elementToFade)
          {
              var element = document.getElementById(elementToFade);
  
              element.style.opacity += 0.1;
              if(element.style.opacity &gt; 1.0) {
                  element.style.opacity = 1.0;
              } else {
                  setTimeout("fadeIn(\"" + elementToFade + "\")", 100);
              }
          }
  
          function fadeOut(elementToFade)
          {
              var element = document.getElementById(elementToFade);
  
              element.style.opacity -= 0.1;
              if(element.style.opacity &lt; 0.0) {
                  element.style.opacity = 0.0;
              } else {
                  setTimeout("fadeOut(\"" + elementToFade + "\")", 100);
              }
          }
          //]]&gt;
      &lt;/script&gt;
   &lt;/head&gt;
   &lt;body&gt;
      &lt;div&gt;
          &lt;div id="slideSource"
                style="width:150px; height:20px;
                      text-align:center; background:green"
               onclick="slidePanel('panel', this)"&gt;
              Take It up
          &lt;/div&gt;
          &lt;div id="panel"
                style="width:150px; height:130px;
                      text-align:center; background:red;
                      opacity:1.0;"&gt;
              Contents
          &lt;/div&gt;
      &lt;/div&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>What am I doing wrong and what is the best way to fade in and fade out an element?</p>