Feed on
Posts
Comments

If you’ve ever used jQuery to fade out an element, you’ve probably discovered that there are a few ways to accomplish the effect. You could use hide(), fadeOut(), or animate() to change an element’s opacity, but what are the differences between these methods and are there any gotchas?

Both hide() and fadeOut() work similarly in that they gradually change an element’s opacity to zero and then change the display style property to none (hide() will also change the height and width of an element to zero). However, while using animate() to change the opacity will look like it accomplishes the same result, it doesn’t change the display style property to none like both hide() and fadeOut() do. Therein lies the gotcha. If you use hide() or fadeOut() to make an element disappear, you can’t use animate() to change the opacity and make the element visible again. Since hide() and fadeOut() also set the display style property to none, animate() can’t do its job because hide() and fadeOut() have effectively hidden the element from animate being able to see it, causing it to remain invisible. To bring make an invisible element visible again that was hidden with hide() or fadeOut(), use show() or fadeIn().

This has tripped me up from time to time, especially when I’m trying to keep an element hidden and then animate a few properties simultaneously as I fade it back in. So while hide() and fadeOut() are quite capable on their own, and show() and fadeIn() work well to make elements visible again, stick with using animate to hide or fade out an element when you want to fade it in later as well as animate other properties at the same time.

The following table quickly shows the differences between jQuery methods when fading an element:

CSS Property Changed
opacity display width/height
hide() X X X
fadeOut() X X
animate() X

The same goes for the reverse process of showing or displaying elements. Show() animates the opacity, display, width, and height CSS properties, and fadeIn() animates the opacity and display properties.

2 Responses to “jQuery hide() vs. fadeOut() vs. animate()”

  1. wasim kazi says:

    Hi,
    You are really given a good explanation but it’s i want to know that there is any diff between hide and fadeout and show and fade in. if they work same so y we need it.

  2. Geedmo says:

    I always come around when I’m confused with these methods and never leave thanks, so..
    Thanks for this so useful explanation!

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>