jQuery fadeOut() Not Working on Absolute Positioned Elements

September 18th, 2013 - Posted by Steve Marks to Javascript / jQuery, Web Development.

I’ve been using jQuery for a few years now and, in this time, must have done thousands upon thousands of hiding and showing elements by using the fadeIn() and fadeOut() functions. Back in the day, hiding and showing elements was commonly done by switching the ‘display‘ style attribute between ‘block‘ and ‘none‘ which resulted in a jerky, jumpy, and confusing transition. The fade functions available in jQuery make hiding and showing items a much nicer experience.

I came across a problem earlier today however when I was trying to fade out an element that was positioned absolute on the page whereby the element would just not hide. No matter what I tried it would just remain on the page. The funny thing is however that the callback function was being executed.

An example of what I was trying can be found below:

$('#hide_trigger').click(function()
{
	$('#my_div').fadeOut('fast', function()
	{
		alert("Finished fading");
	});
});

As you can see, when my link with ID ‘hide_trigger‘ is clicked, the element ‘my_div‘ should be faded out, then the alert should popup when the transition has complete. As mentioned above I was getting the alert, just not a fading element.

The “Solution”

The reason I say the “Solution” is because after hours of investigation I still honestly can’t say why the fadeOut() function isn’t working. My solution to this problem is more a workaround but oddly works and achieves the same end result.

In summary, instead of using the fadeOut() function, I switched it out for the jQuery fadeTo() function which adjusts an elements opacity. I’ve included below the snippet from above that wasn’t working and modified it to use the fadeTo() instead:

$('#hide_trigger').click(function()
{
	$('#my_div').fadeTo('fast', 0, function()
	{
		alert("Finished fading");
	});
});

Whether this scenario is specific to the version of jQuery I was using I’m not sure. I saw recommendations online that suggested I try setting a width, try adding a delay, plus other suggestions, none of which worked so I will use this workaround for the time being in this rare case.

This entry was posted on Wednesday, September 18th, 2013 at 8:58 pm by +Steve Marks and is filed under Javascript / jQuery, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (1)
  1. John says:

    cheers for the tip saved me a headache!