jQuery fadeToggle() plug-in

Categories: jQuery

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"
   $("#my-div").fadeToggle();
   // 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.

Comments

Livio's Gravatar This snippet saved my day. Thanks!
anon's Gravatar Great snippet bu i cant get it to work =/

is there a demo anywhere??

thanks
Dan G. Switzer, II's Gravatar @anon:

You need jQuery for this snippet to work. Are you sure you have jQuery working correctly?

Add Comment



If you subscribe, any new posts to this thread will be sent to your email address.