Thursday, March 29, 2012

jQuery Custom Effects

Although jQuery provides us with a few basic effects like slideDown/Up, fadeIn/Out etc. and a pretty powerful animate function to create animation/effects on any numeric CSS property, a lot of creative people have written some amazing effects/components that will take your breath away. While we do not plan to reinvent the wheel here but down the road, you may also need to create your own effect and would like to access it like

image

Surprisingly, being able to do so is not as difficult as it might seem at first, and can be achieved by adding a new function property to jQuery.fn object as below:

image

The above function simply extends the jQuery object by adding a new method in the jQuery prototype ( jQuery.fn object ). Before diving deep into the implementation, it is important to understand the concept of prototypal inheritance in JS and reading this article will open your eyes for sure.

Coming back, a naive implementation looks like

image 

Here, we delegate the actual work to animate method and toggle the height & opacity of the selected DOM element for the given speed if any, else a default of 400ms is used. It also allows us to specify a callback function to be called after the animation/effect is complete. To accomplish that, we first check whether the passed variable (fn) is actually a function using isFunction and then call the method passing this as the context.

Another important thing to note is that we are returning the jQuery object back from our function so that you can take advantage of chaining like:

image

So this wraps up a short and simple post on how to create custom effects by extending jQuery object. If you have any questions or comments, please leave them as comments.

No comments: