Back to Blog

jQuery fadeTo method fades even the hidden elements

on January 29, 2010

Following code has been tested with jQuery 1.4.1 . Code demo links are the end of the blog .

fadeTo method of jQuery ,strangely, fades event the hidden elements.

Here is html markup.

1<style>
2  #hello p {
3    display: none;
4  }
5</style>
6<div id="hello">
7  <p>this is p inside hello</p>
8</div>
9<p>This is p outside hello</p>

Since the first p is hidden, you will see only one p element in the browser. Now execute following jQuery code.

1$('p').fadeTo('slow', 0.5');

You will see both the p elements.

jQuery goes out of its way to make sure that hidden elements are visible. Here is fadeTo method.

1fadeTo: function( speed, to, callback ) {
2	return this.filter(":hidden").css("opacity", 0).show().end()
3				.animate({opacity: to}, speed, callback);
4}

Also notice that for a hidden element fadeTo operation starts with opacity of zero, while other elements will go down towards zero.

Checkout the same demo in slow motion and notice that while the first p element emerges out of hiding, the other p element is slowing fading. This might cause unwanted effect . So watch out for this one.


You might also like

If you liked this blog post, check out similar ones from BigBinary