Simple Effects Plugins

read 69 comments

jQuery has a nice selection of core animation effects, such as .show('speed') and .hide('speed'), .slideUp() and .slideDown(), and .fadeIn() and .fadeOut(). It even has a couple methods for toggling effects — the aptly named .toggle('speed') and .slideToggle().

All of these methods have optional speed, easing, and callback arguments — although a couple are special cases. The .show() and .hide() methods, when used without a speed, will immediately show and hide the matched set of elements with no animation. When the speed argument is included, the matched elements are shown and hidden gradually by animating their height, width, and opacity simultaneously. The .toggle() method shares its name with a method that takes two arguments that alternate being triggered. All of the other effect methods have a default speed of 400ms.

The Flexible .animate()

jQuery internally uses another method, .animate(), to define these shorthand effect methods, and it makes .animate() available to us to do the same. So, let's create our own method that we can use the same way we would use, for example, .slideToggle().

Custom Animation Methods

Someone on the jQuery discussion list recently asked if there was a .fadeToggle() effect in jQuery. In my reply, I admitted that there wasn't one, but suggested that it wouldn't be too hard to create using .animate(). We just attach .fadeToggle to jQuery.fn and pass in the speed, easing, and callback arguments. Then, we return this.animate() with the effect we want, along with those same arguments:

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

Update

As of jQuery 1.4.4, .fadeToggle() is officially included in the jQuery core file.

Now, when we want to use it, we can treat it the same as any other jQuery method. For example:
JavaScript:
  1. $(document).ready(function() {
  2.   $('#fade').click(function() {
  3.     $(this).next().fadeToggle('slow');
  4.   });
  5. });

Try it out:

Watch me fade.
(Incidentally, Dan G. Switzer saw the discussion-list thread and blogged about it himself. Thanks, Dan!)

To create a method that toggles a fade and a slide at the same time, all we need to do is repeat the process, adding a "height" parameter:

JavaScript:
  1. jQuery.fn.slideFadeToggle = function(speed, easing, callback) {
  2.   return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);  
  3. };

Give this one a try:

Watch me slide and fade.

Blind Toggle

Let's try one more — a "blind" effect. Instead of changing the height of the element, as we do with a "slide" animation, we're going to move the entire element up and down.

The plugin itself will still be fairly rudimentary, but we'll need to set up some CSS to get it to work correctly. Here is the CSS:

CSS:
  1. #box {
  2.   padding: 10px;
  3.   height: 100px;
  4.   width: 100px;
  5.   background: #e459e9;
  6. }
  7. #box-outer {
  8.   overflow: hidden;
  9.   height: 120px;
  10.   margin: 20px;
  11. }

Notice that we have two "boxes" styled here. The first one will be in the markup itself, but the second one, since it's only being used to help with the effect, will be created by our script. The important properties here are #box-outer's overflow: hidden and height: 120px. The hidden overflow will allow #box to seemingly disappear as it moves up, while the height (which is #box's height plus its top and bottom padding) will keep the rest of the page from shifting along with the box.

Now, on to the plugin code:
JavaScript:
  1. jQuery.fn.blindToggle = function(speed, easing, callback) {
  2.   var h = this.height() + parseInt(this.css('paddingTop')) + parseInt(this.css('paddingBottom'));
  3.   return this.animate({marginTop: parseInt(this.css('marginTop')) <0 ? 0 : -h}, speed, easing, callback);  
  4. };

While relatively simple, there are a couple things here that might be confusing to jQuery/JavaScript beginners. The first line inside the function declares a variable for the height of this, plus the top and bottom padding ("this" here refers to whatever is matched by the selector in the script that uses the plugin). The parseInt() JavaScript function function looks at a string from left to right until it encounters a non-numeric character. The string of digits up to that character is converted into an integer, stripping off the trailing non-numeric character. So, "10px" becomes 10.

The line that follows animates the marginTop property. It uses a ternary (conditional) operator to test if marginTop is less than zero. If it is, the element's marginTop property animates to 0; if not, it animates to negative the value stored in the h variable.

Finally, we're ready to put this plugin to use:

JavaScript:
  1. $(document).ready(function() {
  2.   var $box = $('#box')
  3.     .wrap('<div id="box-outer"></div>');
  4.   $('#blind').click(function() {
  5.     $box.blindToggle('slow');  
  6.   });    
  7. });

Line 2 "caches" our selector, since we're using it more than once. Then we wrap a div around the "#box" div and bind a click handler to a button. Let's see how this one looks:

Blind me up. Blind me up. Blind me up.

So, now we have three simple effects methods that we apply to our sites for a little extra flair.

jQuery UI

For really cool effects, check out the demos of jQuery UI effects.

comment feed

69 comments

  1. Oops. Good catch, Braden. Fixed.

  2. John Kitson

    Nice effects - I like the slideFadeToggle since it has a better default behaviour in IE than SlideToggle, which seems to make the contents of the DIV jump a few pixels on completion of the animation. I'm sure that is fixable with CSS but slideFadeToggle just looks slicker. :) Thanks Karl.

  3. Bohdan Ganicky

    Looks like you've confused BLIND and SLIDE. I guess slide stands for moving the entire element and blind stands for just changing the height of an element. Anyway, thanks for this nice howto...things looks so simple now :)

  4. andrea varnier

    thanks Karl, you're great!! :)

  5. D Jones

    I used the fade effect to fade a background image behind some images, but now I cannot make not affect the siblings.

    // do something on document ready
    $(".thumbnailbg").fadeTo("fast", 0.0); // This sets the opacity of the thumbs to fade down to 0% when the page loads
    	$(".thumbnailbg").hover(function(){
    		$(this).fadeTo("slow", 1.0); // This should set the opacity to 100% on hover
    	},function(){
       		$(this).fadeTo("slow", 0.0); // This should set the opacity back to 0% on mouseout
    	$(".thumbnail").removeClass("thumbnailbg").show(); // This should make the thumbnail show always
    	});
    });

    Located Here.

  6. Jagan

    Hi,
    i'm working on vista gadgets. wanted to know if JQuery works in sidebar in vista, does it have any restrictions with the same. is it possible to create the same kind of effects in the sidebar gadget...?
    if so can u plz let me how to go about it...?

    Thanks

  7. Hi Jagan,

    Don't know anything about Vista. You might have better luck on the jQuery discussion list.

  8. jQuery is the best!
    I use it everywhere!!!

  9. The only problem is that almost all jQuery components are not so well documented.

  10. Great blog! I've build a tumblr theme with the Slide-Fade effect over here.
    Now I've got the problem that before the .hide removes all content-bodys it is loaded completely. With an slow internet connection it looks not so good. How can I prevent the hidden posts from loafing? I' stumbled over this plugin. But can I use it for my aim?

  11. Some really nice examples, i find that some of the effects in jQuery can be a big lagg-ish on some of the sites i have implimented them in, although on this website they seem to work so smoothly!

  12. Sehr cooler Code, danke
    toni

  13. Florian

    Hi Karl,

    Any idea why this code isn't working anymore when copying the fx.js and fx.slide.js
    from http://www.learningjquery.com/2007/02/more-showing-more-hiding into my template?


    //Checkbox select all/none
    $("#checkboxes_all").toggle(
    function() {
    $('input[@type=checkbox]').attr('checked', 'checked');
    },
    function() {
    $('input[@type=checkbox]').removeAttr('checked');
    });

    As soon as I put both snippets into it I can click and nothing happens :-/

    thanks
    Florian

  14. Hi Florian,
    Not sure which fx.js and fx.slide.js files you're referring to. They aren't listed anywhere on the page you link to above.

    If you're using jQuery 1.2 or higher, you should omit the "@" symbol in the selector. Actually, jQuery has a special ":checkbox" selector, so you could use $('input:checkbox') Also, try using .attr('checked', true) instead of .attr('checked', 'checked').

    Hope that helps.

  15. is there a vertical .blindToggle ?

  16. Geo

    Great, thanks :)

  17. Dan

    How would I make it toggle to say 50% opacity and than toggle back to 100%?

  18. Hi Dan,
    Try something like this:

    jQuery.fn.fadeSomeToggle = function(speed, easing, callback) {
      var op = $(this).css('opacity');
      return this.animate({opacity: op != 0.5 ? 0.5 : 1.0}, speed, easing, callback);
    };

    That should do it.

  19. pablo

    Could I use this events of jQuery to slide panels from right to left?

  20. Jquery is the best!! I use it on my face…

  21. I am a jQuery plugin developer and I never knew that using 'toggle' inside animate is possible. Thanks for this great tip.

  22. Jquery is very gr8. Its very useful for development with static as well as dynamic pages.

  23. Josh

    Love this tutorial. One question on the blind toggle, how can you make the panel start out hidden at the top?

  24. Hey Bradon, nice tutorial, but i cannot manage to make it start HIDDEN first tan toggle out and in. Like Josh said.

  25. George

    Presumably to make something start hidden you could call

    $('#blind').hide();

    first of all within the $(document).ready(...);

    That way it will be visible for users without javascript.

    GC

  26. Peter

    Is is possible to have something slideUp and FadeOut at the same time? Can effects be chained in this manner?

  27. Hi Peter,

    Look at the slide-fade toggle example. That one slides an element and fades it at the same time. And yes, effects can be chained.

  28. I'm fairly new to jQuery, but I've been using several of the effects repeatedly. Now I'm stuck with an effect that I really need, but cannot seem to find a way to make it work in jQuery.

    Basically all that I want is a Blind Toggle effect turned upside down. I want the element to slide down out of view and then slide back up into view. It sounds simple enough considering all of the things you can do with jQuery, but I just can't find a way to accomplish this.

    The two effects slideUP (hides) and slideDown (reveals) work in the exact opposite manner that I'm needing, otherwise I would just use that. Any ideas?

  29. Is there a way to get this Fade effect and or slide effect in jQuery on a mouseover event and can you either tell me or help me on how to implement this. Please email me with the solution. Don't know when I can get back to the blog.

  30. Rohit

    Hello Karl,
    Thanks for such a nice example.I have one problem i have one table with rows containing select box in each and having name "mytable".when i use fadeToggle() ,i just don't want any value from select box of mytable
    how i can manage this.Will you suggest me the way

  31. Aaron

    This is great! I noticed on bold text when you fade and slide it gets pixelated when it animates the show or hide. Any ideas or how to fix this?

    Thanks!

    • Hi Aaron,
      IE6 and IE7 both have problems with opacity animations. For IE6, the solution is to give the element you're fading a background color. For IE7, the solution is a little more complicated. Check out Mike Alsup's Fade Test for that.

  32. Robin

    Karl:
    Educate a beginner . . . how can I reverse the order of your toggle in Blind Toggle; ie, open a page with #box (and #box_outer) closed or 'up' and drop down when toggled?

    • Hi Robin,
      You can either give #box a display:none; in the stylesheet or change line 2 to var $box = $('#box').hide()

      • Robin

        K:

        Tried both CSS and changing jquery code - both 'closed' #box, but it wouldn't open on toggle. Does .hide() need to be part of jquery.blindToggle.js?

        • Esme

          I managed to get this to work by doing this:

          
          #box {
            height: 250px;
            width: 450px;
            margin: -260px 0 0 0;
          }
          #box-outer {
           overflow: hidden;
           height: 260px;
           margin: 0px;
          }
          
        • James

          Robin,

          did you manage to get this working any other way than using minus margins?

  33. Robin

    Karl:
    Should have included this in previous comment: How can I place button and boxes in a z-index layering so they 'cover' another div when toggled down? I've used position:relative for the div I'm covering and position:absolute, z-index: 100 for the button and boxes div's - works fine in F'fox, but leaves small portion of box showing over button in IE. Ideas welcome.

  34. Robin

    K:

    Ok, solved IE z-index problem by layering button 'above' #box, #box_outer with absolute positioning and higher z-index.

  35. Robin

    Tried following:

    
    $(document).ready(function() {
      var $box = $('#box')
    	.wrap('<div id="box-outer"></div>');
    	$('#blind').click(function() {
    	$box.blindToggle('slow');
    	$box.show();
      });
    });
    

    along with CSS #box display:none, and displayed #box 'closed' on page load, but toggle pushed blind down first, then up. Again, ideas welcome.

  36. Mmm... Nice! Thank you very much for the lessor Karl!

  37. Hi Karl,

    Can please tell me how to achieve "Slide-up/Fade Out" similar to Slide-Fade toggle. I tried searching around the web, haven't any solution

  38. Hi Karl,
    Just found the solution for my previous comment on the discussion thread where you explained it.
    Over here http://groups.google.com/group/jquery-en/browse_thread/thread/eb50e213ae7d761e

    Thanks a lot :)

  39. Hi, Karl. I'm using prototype right now, but I'm on my way to transitioning over to jQuery. Is there anyway to make these work on links instead of buttons like prototype does? Go to my site and click on the menu, I'd like to do that with jQuery.

    • Hi John,

      Yes, it's very easy to make them work with links. You can, in fact, make them work on any element you wish.

      With links, the one thing you'll need to add is a return false; line. For example, if you have a link with an id of "mylink," you could bind it like so:

      $('#mylink').click(function() {
        $('#some-other-element').blindToggle('slow');
        return false;
      });
      
  40. RajD

    This is a great article. The problem I have is the need to hide some other html elements after the slideFadeToggle is called. Example would be to hide some images when the div is expanded and show them after the toggle closes the div.

    I thought I'd found the solution at http://jsbin.com/ojuju/edit, but the else statement doesn't fire with slideFadeToggle. It fires when I use the standard toggle() method.

    • Randy

      I would pass a callback function to the slideFadeToggle, and then do what I wanted with the other elements within that callback function. You could check the css opacity or height from within the callback, to determine if the element had just finished fade-sliding out or fade-sliding in.

  41. I don't seem to be able to get fadeToggle to work.

    I have placed the code:

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

    In the jquery-1.3.2.js file but I suspect that I have placed it in the wrong place. I put it at the end just before the final

    });
    })();

    closing brackets. It seems to be the logical place as it is after the closing brackets of the preceding function.

    However when I run my trial page I get te message that:

    'object does not support this property or method'

    I am trying to call it through a function:

    
    //'#t1' is the element I wish to slide and fade
    function sfade(){
        	$('#t1').next().fadeToggle('slow');
    };
    

    in a separate .js file (which I have linked correctly as the normal slides and fades work)

    anyone help?

    • I wouldn't put it in jquery-1.3.2.js, simply because it'll too easily be lost if you ever want to upgrade to a newer version of jQuery.

      The problem with your code, though, is that you're creating a new method called slideFadeToggle and then calling fadeToggle.

      • arrrgh! it's true..

        I'm calling up a method that doesn't exist. What a moron!

        Ta

      • where should I put it then?

      • Sorry to bug you Karl...

        I'm a bit puzzled with the coding. I have called the function successfully and now have the custom animations in their own .js file and everything works fine if, and only if I remove the .next()

        What purpose does the function .next() serve in the code?

        I am using

         function sfade(num){
            	$('#t'+num).slideFadeToggle(500);
        };

        To call the sldeFadeToggle function,
        Which works fine, but the code here:

         function sfade(num){
            	$('#t'+num).next().slideFadeToggle(500);
        };

        doesn't respond at all (but causes no error)

        One other question...

        is it possible to slide and fade with different timing?

    • However, having corrected that error - it still does not work...

      this is in jquery_mod.js

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

      this is in slides.js

      
      function sfade(){
          	$('#t1').next().slideFadeToggle('slow');
      };
      

      where '#t1' is the div to be slid and faded. I have an tag to call the function.

      link to click 

      • looks like using the more than and less than has messed up the message..

        This is the function call code:

         <a href='#null' onClick=sfade();>Stoichiometry </a>
        • You shouldn't be using the .next() method in your code. It's a DOM traversal method (more info here). I used it with $(this) in the article merely as an example. It was inside a click handler, so it basically was saying, find the next sibling ( .next() ) of the clicked element ( $(this) ) and do something to it.

          I'm not a big fan of putting event handlers inline (e.g. <a onclick="...">), but whether you do it that way or not, don't forget to also return false.

  42. I'm trying to implement the "Blind Toggle" method in a WordPress website and would like to have a drop down for each of the comments sections for the posts in a loop. Since I'm going to have several "Blind Toggle" sections in one page, how should I structure the jquery code to accommodate for each of the sections while keeping it dynamic? I know each section will need to have a unique name...I'm just not sure how to implement the code? I'm up for any suggestions...thanks!

    -David

  43. Abhishek

    @Karl
    Its a late feedback, but really appreciate learning custom UI effects. Got one question in blind effect though, the current impl. doesn't take into account any box shadow (css3 style now supported by latest n greatest browsers), while deciding on marginTop value. Any thoughts?

  44. Aldo

    Wowwww... I like JQuery

  45. Awesome, works like a charm through all browsers that I've tried. Thanks for the plugin

  46. Hey Karl,

    Thanks for such good tutorial. I am trying to give fade effect to my project which is using slideViewer 1.2. ( http://www.gcmingati.net/wordpress/wp-content/lab/jquery/imagestrip/imageslide-plugin.html )

    But now success. Can give me an idea how can i slideviewer pro to fade instead of slide?

    Thanks,
    Kumar Sekhar

  47. I would I have the opacity start at zero and go to 100? (reverse the toggle on load)

    Thanks!

  48. Crystal

    How would I get this to work if, i wanted it to be hidden and than when you hover the image (button) it slides out to the bottom, right or left?

  49. alanoPL

    IE7 Opacity Fix:

    Add the following CSS code to the faded box:

    position: relative;
    zoom: 1;

  50. CJ

    what are the jquery codes to fadetoggle automatically without clicking anything ?

32 Pings

  1. [...] Simple Effects Plugins- Nice animation effects that can easily toggle, hide, show, fade, slide [...]

  2. [...] Simple Effects Plugins- Nice animation effects that can easily toggle, hide, show, fade, slide [...]

  3. [...] Simple Effects Plugins- Nice animation effects that can easily toggle, hide, show, fade, slide [...]

  4. [...] 28) Simple Effects Plugins- Nice animation effects that can easily toggle, hide, show, fade, slide elements. [...]

  5. [...] Simple Effects Plugins- Nice animation effects that can easily toggle, hide, show, fade, slide [...]

  6. [...] Simple Effects Plugins- Nice animation effects that can easily toggle, hide, show, fade, slide [...]

  7. [...] To convert any of these slides into a plugin for convenient reuse, see Simple Effects Plugins. [...]

  8. [...] To convert any of these slides into a plugin for convenient reuse, see Simple Effects Plugins. [...]

  9. [...] Tutorials for Designers Simple effects plugins 12 jquery tool tips for web developers If you have any suggestions or know of any other great [...]

  10. [...] Simple Effects Plugins Permite que você adicione efeitos em seus objetos de uma maneira super simples. Efeitos como “toogle”, esconder, mostrar, fade-in e fade-out e slide. [...]

  11. [...] Simple Effects Plugins Permite que você adicione efeitos em seus objetos de uma maneira super simples. Efeitos como “toogle”, esconder, mostrar, fade-in e fade-out e slide. [...]

  12. [...] Simple Effects Plugins- Nice animation effects that can easily toggle, hide, show, fade, slide elements. [...]

  13. [...] Simple Effects Plugins- Nice animation effects that can easily toggle, hide, show, fade, slide [...]

  14. [...] Simple Effects Plugins-Nice animation effects that can easily toggle, hide, show, fade, slide elements. [...]

  15. [...] 76. Simple Effects Plugins (演示地址) [...]

  16. [...] Simple Effects Plugins – Learning jQuery [...]

  17. [...] Simple Effects Plugins- Nice animation effects that can easily toggle, hide, show, fade, slide [...]

  18. [...] Simple Effects Plugins [...]

  19. [...] 28) Simple Effects Plugins- Nice animation effects that can easily toggle, hide, show, fade, slide elements. [...]

  20. [...] the demo of above code http://www.learningjquery.com/2008/02/simple-effects-plugins just go to site and click on blind toggle button just to see how i want the things. i want when [...]

Sorry, but comments for this entry are now closed.