Monday, August 22, 2011

Using jQuery to fade in your webpage progressively

Okay, so something I want to do, now that I'm able to really focus on expanding my web knowledge, is post some things I learn along the way. Hopefully they'll be helpful to someone.

So, I was trying to find a way to fade in the sections of my website, one after the other. A simple query fade of the background took everything from white to visible, which I didn't like. Fading in body items one by one made the page expand while they were loading - also not a great effect.

This is what I came up with. The page holds the background and will progressively fade in any element you wish, one by one.

Demo Page - See the effect

<script>
$(document).ready(function() {
function fadePage() {
// Target the tag(s) you want to effect with the fade
var fadingTag = "div";

var delay = 0; // Initialize delay - Should start at 0
var delayStagger = 600; // Delay stagger - Time between elements fading in

// Find out how many elements you need to hide
var fadingNum = document.getElementsByTagName(fadingTag).length;

// Get and fix the overall document height before it disappears (which will happen when elements are hidden)
var pageHeight = $(document).height() + "px";
$("body").css("height", pageHeight);

// Hide all targeted tag(s)
$(fadingTag).css("display", "none");

// Fade each targeted tag in, one by one
for (var i = 0; i < fadingNum; i++){
$($(fadingTag).get(i)).delay(delay).fadeIn(delayStagger);
delay += 350;
}
}

fadePage();

});
</script>


All you have to do is add the name of your tag to the "fadingTag" variable. In this demo, I have all divs fading in, one by one. Targeting classes/ids/etc is also VERY EASY with jQuery. Some examples:

// Target divs with class of "test"
var fadingTag = "div.test";

// Target all elements with a class of "test"
var fadingTag = ".test";

// Target all images
var fadingTag = "img";

// Target all images inside a paragraph
var fadingTag = "p img";

jQuery is just endlessly flexible.

If you want to adjust the timing, just change the delayStagger variable.

Did you find this useful? Please add your comments. :)

1 comment:

Bangaloreweb guru said...

The blog was absolutely fantastic! Lot of great information which can be helpful in some or the other way. Keep updating the blog, looking forward for more contents...Great job, keep it up..
Website Designing Bangalore | Website Development Bangalore