Videos | Podcasts

Creating Fade In Fade Out Effect Using JQuery
AzamSharp
Published Date: 2/3/2009 1:13:12 PM
Views: 2780

Abstract:
In this article we are going to use JQuery to create a fade in fade out effect. The fade in fade out effect can be used to notify the user that some operation has happened. The fade in will capture the user's attention and the fade out will make sure that the space is not occupied by the stale message.

Recommend Reading:

If you are new to JQuery then we suggest that you check out the JQuery documentation about using the effects.

http://docs.jquery.com/Effects

Implementing Fade In Fade Out Effect:

JQuery has many effects already defined in its strong belt of tricks. This includes fadeIn, fadeOut, slideUp, slideDown etc. Unfortunately, the FadeInFadeOut effect is not included in the library. But that is OK! because we can easily add this effect to the jQuery functions and reuse the effect at our own pleasure.   

Here is the one way to create the effect:

$("#divMessage").html("Item has been saved").fadeIn(2000, function()
{
    $(this).fadeOut(2000);         
});


First, the fadeIn is fired and after 2 seconds the callback function is fired which in turn fires the fadeOut function. This will work as expected but writing this amount of code everytime we need a fadeInFadeOut effect is just too much. Let's see how we can reduce some code.
 
In the code below we have extended the fn (function) of jQuery base library by attaching our own personal function called fadeInFadeOut.


jQuery.fn.fadeInFadeOut = function(speed) {

        return $(this).fadeIn(speed,

        function() {

            return $(this).fadeOut(speed);

         });
    }


Now we can use the above function like this:


 $("#divMessage").html("Item has been saved").fadeInFadeOut(2000);


And here is the effect:



There is another way to produce the same effect. Check out the following code:


$("#divMessage").html("Item has been saved").fadeIn(2000).fadeOut(2000);


In the above code the message will fadeIn at the rate of 2 seconds and then fade out after 2 seconds.

Conclusion:

JQuery provides many build-in effects to ease the developer pain. JQuery also provides the animate function which is used to create custom animations. You can also extend the JQuery functions by attaching your own functions.

I hope you like this article, now go and get high!



Did you like this article?
kick it on DotNetKicks.com Submit
Similar Articles

Creating Beautiful Dialogs Using JQuery UI

JQuery jqGrid Export to Excel Using ASP.NET MVC Framework

GridView Confirmation Box Using JQuery BlockUI

Hide Progress Indicator When IFrame is Loaded

Pimp Up List Sorting Using JQuery

Enter Comment/Feedback

 
 
 
 
 

Comments/Feedbacks