IE7 and IE8 Ignoring Opacity When Using jQuery fadeIn()
I’ll dive straight into this one by explaining the problem I came up against earlier this week whilst cross browser testing a feature in Internet Explorer 7 and 8.
Let’s look at the following element:
What we’ve got here is a black div with 50% opactiy, hovered over the top of some words. Due to the opacity it appears grey and we can see the words through the div.
I’ve included below the HTML and CSS used to create this:
<!DOCTYPE html> <html> <head> <style type="text/css"> #myDiv { display: none; position: absolute; width: 250px; height: 250px; background-color: #000; -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; /* IE 8 */ filter: alpha(opacity=50); /* IE 5-7 */ -moz-opacity: 0.5; /* Netscape */ -khtml-opacity: 0.5; /* Safari 1.x */ opacity: 0.5; /* Good browsers */ } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { $('#myDiv').fadeIn(); }); </script> </head> <body> <div id="myDiv"></div> I'm underneath the div </body> </html>
As you’ll see in the code above, the div by default has a ‘display’ style set to ‘none’ meaning it’s not shown by default. We then fade in the div when the page is loaded using jQuery.
The Problem
This all works fine until we come to IE7 and IE8 however. In this scenario we get the following when the page has loaded:
Hmm… A solid black block with not an ounce of transparency in sight. Not exactly what we had in mind right?
The Solution
The solution is thankfully a quick fix and involves us adding just one more line of code before we call jQuery’s faceIn() function like so:
$(document).ready(function() { $("#myDiv").css('filter', 'alpha(opacity=50)'); $('#myDiv').fadeIn(); });
By re-applying the opacity prior to performing the fading it now works across all browsers.
You are my hero for the moment. Thank for taking the time to post this! I’ve spent hours (at least a couple) reading about hasLayout and other stuff. Ugh!!
Thanks again!!