Search code examples
jqueryeffectsfading

JQuery - div fading trouble


I have div, which has id 'content'. It's visible.

<div id="wrapper" style="display:block">
  <div id="content">
    Some text
  </div>
</div>

Now I want to fade it out:

$('#wrapper').fadeIn( 1500 );
$('#content').click(function(){
   $(this).fadeOut( 1500 );
});

And nothing happens. But when I wrote:

$('#content').fadeIn( 1500 );

It hides and then shows again.


Here is css

#content
{
    height: 100%;
    width: 100%;
}

Browser: Firefox 3.5.3 under Linux Gentoo

upd

When I type code:

$('#content').hide();

It hides correctly.


upd

I've solved problem... I can't understand, why did it was... Just replaced jquery.min with jquery


Solution

  • If I understand your question, you have two problems: the content doesn't fade in, and when you click it, the content doesn't fade out.

    Both problems are probably caused by your script executing before the wrapper and content divs have appeared in the document. If your <script> tag is in the <head> of your document, then $('#wrapper') won't find anything to fade in and $('#content') won't find anything to attach a click handler to.

    The best solution is probably to defer doing anything until the document is loaded, by using ready:

    $(document).ready(function () {
      $('#wrapper').fadeIn(1500);
      $('#content').click(function () {
        $(this).fadeOut(1500);
      });
    });
    

    Alternatively you could put your <script> tag after the <div> tags in the body.

    When you fix this problem the content will fade in, but it won't be smooth because the wrapper div is initially visible—you have style="display:block" on the wrapper div. You need to make that display: none; instead so that the wrapper div is hidden while the page is loading.

    Here is a complete file which works:

    <html>
    <head>
    <style type="text/css">
    #wrapper
    {
        display: none;
    }
    
    #content
    {
        height: 100%;
        width: 100%;
    }
    </style>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
      window.alert("Couldn't load jQuery");
    </script>
    <script>
    $(document).ready(function () {
      $('#wrapper').fadeIn(1500);
      $('#content').click(function () {
         $(this).fadeOut(1500);
      });
    });
    </script>
    </head>
    <body>
    <div id="wrapper">
      <div id="content">
        Some text
      </div>
    </div>
    </body>
    </html>