Please navigate to the bottom of the page for Table of Contents

Saturday, June 4, 2011

jQuery fadeIn, fadeOut and fadeTo effects

jQuery lets you easily add effects such as fading in/out, sliding in/out, and expanding/contracting. Anyone claiming to to know jQuery should make themselves very comfortable in the effects provided by jQuery. In this post we will explore the basic jQuery effect of fading in and out using examples. The jQuery API browser (http://view.jquery.com/trunk/tools/api-browser/) is an excellent source of short descriptions and great examples.

Explain fadeIn(), fadeOut() and fadeTo() effects

fadeIn() and fadeOut() manipulate the CSS opacity property to to show or hide an element. In the simplest forms, they can be called with no arguments as shown below:

$("img").fadeOut()

For more complex animations, both the functions also accept optional duration and callback arguments. Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively. If any other string is supplied, or if the duration parameter is omitted, the default duration of 400 milliseconds is used.
<div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />
With the element initially hidden, we can show it slowly:
$('#clickme').click(function() {
$('#book').fadeIn('slow', function() {
// Animation complete
});
});


fadeTo() works slightly differently from fadeIn and fadeOut. It expects a target opacity argument and animates the change from the element’s current opacity to this target. The function signature looks like


.fadeTo( duration, opacity, [ callback ] )

duration: string or number determining how long the animation will run.
opacity: number between 0 and 1 denoting the target opacity.
callback: function to call once the animation is complete.

For the following html snippet, the following script animates first paragraph to fade to an opacity of 0.33 (33%, about one third visible), completing the animation within 600 milliseconds.


<p>     
Click this paragraph to see it fade.
</p>
<p>
Compare to this one that won't fade.
</p>

$("p:first").click(function () 
{
$(this).fadeTo("slow", 0.33);
});

I encourage the user to read more in detail about the fading effect on the official jQuery API documentation at http://api.jquery.com/category/effects/fading/.

1 comment:

  1. JQUERY FADE IN FADE OUT

    http://fundapass.blogspot.in/2012/07/jquery-fade-in-fade-out.html#more

    ReplyDelete