Saturday, July 20, 2013

Javascript to Dynamically Change the Background Color of an Element for IE


You can change the background color easily in Chrome, Safari and Firefox.

But for IE, you cannot change it using the easy way like the other browsers are doing it.

Here's the solution (simplified for easy reference):

var ie = (navigator.userAgent.indexOf("MSIE") != -1);

if (!ie) {
   document.getElementById('MyElemID').style.backgroundColor = "#AABBCC";
}
else {
   document.getElementById('MyElemID').style.backgroundColor = "rgb('AA','BB','CC')";
}


Therefore, if you want to accommodate for all browsers, one needs to think of color as RGB components. You either break up the RGB component to suit IE's requirement or combine RGB components into a string to suit the need of Chrome, Safari or Firefox.

Updated on 4th of August 2013:
It is better to use rgb(170,187,204) instead of rgb('AA','BB','CC') stated earlier.



No comments:

Post a Comment