In many occurrences i find myself wanting to fade in an element on the page and then immediately fade it out as a way to convey that something happened in a non-obtrusive way.
To do that I need to call the fadeIn and fadeOut jQuery methods in sequence. This can be done easily because fadeIn accepts a callback as a second parameter which will be called when the animation completes.
Easy as it is to do I still find it annoying that i have to call two separate methods for an action i wish to be done as one so naturally since it is so easy to extend jQuery I wrote a little extension that does just that.
Here is the code:
To use it you just need to add this code somewhere on your page or (preferably) in a separate JS file as long as its after the inclusion of jQuery and before you intend to use it.
Once you’ve added this code using the function is the same as using any jQuery method.
The new method that will be added to jQuery is called: fadeInOut and it accepts 3 (optional) arguments: inTime, outTime and callback.
The inTime is the duration of the fadeIn animation.
The outTime is the duration of the fadeOut animation.
The callback is a function to be called when both animations complete.
A few examples of using the fadeInOut method:
There are 4 ways you can call the method:
1) No arguments – The fade in and out will both be called with a default duration of 1 second.
2) One argument – If its a number it will be used as the duration for both in and out animations, if its a function it will be used as the callback and the 1 second default will be applied.
3) Two arguments – If both are numbers they will be used for the duration of the in and out animation respectively. If the second is a function it will be used as the callback and the first number will be used as the duration for both animations.
4) Three arguments – first two arguments will be used for the animations in and out duration respectively. The 3rd argument will be used for the callback.
You can easily change the default duration time by changing the value passed to the “defaultDur” variable.
Hope you find it useful.