jQuery fadeTo method fades even the hidden elements

Neeraj Singh

Neeraj Singh

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.

<style>
  #hello p {
    display: none;
  }
</style>
<div id="hello">
  <p>this is p inside hello</p>
</div>
<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.

$('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.

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

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.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.