Fade in content on page load

Hi,

I’ve created a function to fade in content (a particular div) when the page loads, but I have an issue with it. If javascript is disabled, I want the div to be visible, therefore in the css the div is not hidden and opacity is set to 1 (ie no transparency). My script changes the opacity to 0 when the page loads, and then fades it in to a specified value.

This works fine, but the problem is that when the page loads, the content is visible for a fraction of a second, then it disappears and fades in as intended.

How can I get the content to fade in without it being visible for that fraction of a second first.

Here’s my code, I’m using the core library from the book Simply Javascript, and the jQuery library.

var FadeIn =
{

 init: function()
 {

  var content = Core.getElementsByClass("fade");
  FadeIn.makeTransparent(content);

  $(".fade").fadeTo(3000, 0.9);

 },

 makeTransparent: function(content)
 {

  $(".fade").css("opacity", 0);
  $(".fade").css("filter", "alpha(opacity=0)");

 }

};

Core.start(FadeIn);

Thanks

Richard.

Core.start waits until the page has finished loading.

What you want is for the code to run sooner than that. At the end of the body, just before the </body> you should run the script, which will get it going as soon as possible.

So if the Core.start was done as a separate line from the library itself, here is how the change would look.


<html>
<head>
    <script src="fadein.js"></script>
    <script>
        // Core.start(FadeIn);
    </script>
</head>
<body>
    <script>
        FadeIn.init();
    </script>
</body>
</html>

thanks, that works a treat!

Having thought about this a bit more in my sleep (that always works), i realised that I could use $(document).ready() from the jQuery library to do the same thing as Core.start. The advantage is that $(document).ready() waits until the document is ready to be manipulated, whereas Core.start waits until the document has finished loading.

This means I can modify my code to keep all the javascript within the external .js file, instead of having to put <script> tags before the </body> tag.

Here’s my modified code, hope it helps someone out there :slight_smile:

var FadeIn =
{

 init: function()
 {

  var content = Core.getElementsByClass("fade");
  FadeIn.makeTransparent(content);

  $(".fade").fadeTo(3000, 0.9);

 },

 makeTransparent: function(content)
 {

  $(".fade").css("opacity", 0);
  $(".fade").css("filter", "alpha(opacity=0)");

 }

};

$(document).ready(function()
{
 FadeIn.init();
});

You are supposed to place as much of your javascript at the end of the body for performance reasons anyway, but you’ve found another method that works for youi so rock on.