Cross-Browser Image Opacity

Here is an example of using JavaScript to apply opacity based on what the browser supports. Unfortunately not all browsers behave the same so we need to test this first before applying the opacity. There are many other ways to accomplish this, but this is the simplest way using [vanilla] JavaScript.

First we need our images to test with. The first image** of the mountains will have opacity if the browser supports the 'opacity' style attribute. The second image** of the beach uses the 'filter' style attribute to give us the same effect. Depending on what browser you are viewing this post with, you will only see one of the two images with opacity applied.
<img id="image1" src="/path/to/image1.png" />
<img id="image2" src="/path/to/image2.png" />
Next we setup the JavaScript to test for 'opacity' and apply the style. If the attribute is not available, it will then test and apply opacity using the 'filter' attribute. We have also made it so that the image with the opacity applied is now the larger of the two.
if('opacity' in document.documentElement.style) {
   var img = document.getElementById('image1');
   img.style.opacity = ".5";
   img.style.height = "120px";
   img.style.width= "150px";
} else if('filter' in document.documentElement.style) {
   var img = document.getElementById('image2');
   img.style.filter = "alpha(opacity=50)";
   img.style.height= "120px";
   img.style.width= "150px";
}
Applying the above code we will see our results below. For example, if you are on Chrome you should see the mountain image (image1) larger with opacity applied using the 'opacity' attribute. If you happen to be on an older version of Internet Explorer, you will see the beach image (image2) larger and with opacity applied via the 'filter' attribute.



** - both images are linked from Wikipedia, I do not claim ownership/authorship of either image.

No comments:

Post a Comment