jQuery fadeToggle() plug-in

Posted by Dan on Feb 6, 2008 @ 8:25 AM

Karl Swedberg posted this 3 line nugget to the jQuery mailing list this morning and I thought it was worth of blogging. It uses a technique I was previously unaware and that's the animate() method allows for toggling of opacity. This might be a commonly known feature, but I rarely use the animate() method directly—which is probably why I wasn't aware of the feature.

Anyway, here's Karl's code:

jQuery.fn.fadeToggle = function(speed, easing, callback) {
    return this.animate({opacity: 'toggle'}, speed, easing, callback);

This creates a simple jQuery plug-in that you can now use like:

// attach the onclick event to each anchor tag with a class of "div-toggle"
$("a.div-toggle").click(function () {
    // fade-in/out the element with the id of "my-div"
    // return false to prevent the anchor tag from following the href rule
    return false;

You can also pass in arguments to control the speed, easing effect or the callback to run after the fading is complete. If you want to use the callback argument without using the speed or easing arguments, just pass those arguments a value of null.

Categories: jQuery


Add Comment

Leave this field empty