jQuery Quicktip #3 – Fade (Fading In And Fading Out)

Posted on by Matt

Time for another jQuery Quicktip. This time, the fade function. I’ve been having to use the fade function on a site recently, so i thought i’d share a quick tip.

Like most of jQuery, it’s pretty simple to apple the fade function to an element.

First of all we wait for the DOM to be ready, this should be familiar:

$(document).ready(function(){

});

Now we’ve done that we use the built in fade function to fade the element up;

$("#picture_holder").fadeTo("slow", 1.0);

});

We’ve used the example with an id of “#picture_holder” in this example. The first property in the brackets after the the fadeTo function is the speed of the fade, here you can use the term slow or fast or alternatively use a number (remember to remove the ” ” around the slow text) the second property is the opacity of what it is going to fade to, in this case 1.0 is an opacity of 100%, with 0.5 being 50% percent and so forth.

If you want to fade an element in from load then you need to set its opacity before hand. This is easy to do in jQuery too:

$('#picture_holder').css('opacity', 0);

This sets the “#picture_holder” to have an opacity of 0%. We put this before the the fade statement and the the opacity will fade from 0% to 100% .

The full function is:


$(document).ready(function(){
$('#picture_holder').css('opacity', 0);
$("#picture_holder").fadeTo("slow", 1.0);
});

Have fun!

Leave a Reply