There are a lot of examples and tutorials about how to create grayscale images using CSS , CSS3 and JS, but while developing a project for one of my clients, I found out that there is no solution that would be cross-browser compatible and would support the latest Internet Explorer 10 and 11 versions. This is the reason I came up with a solution of my own and decided to share it with you.
Grayscale filter has been natively supported by Internet Explorer since version 6, but recently Microsoft decided to remove this native CSS filter and since version 10, IE does not display grayscale images using the old technique.
This is the reason why we now have to turn to grayscale JS solution. Besides this, Microsoft has released the new IE11, which is trying to hide as a different browser. Now Internet Explorer 11 has changed its user-agent and pretends to be a Gecko or WebKit browser. This is a pretty nifty move by Microsoft in order to render new IE11 on most browsers as a Gecko browser and not like the previous versions with MSIE user-agent (we all know that there are a lot of websites that check for MSIE user-agent and bring up non-standard markup). So I had to overcome this new problem as well – checking the user-agent and firing only the SVG (Scalable Vector Graphics) grayscale JS solution that is intended for IE10+ (IE6-9 support CSS grayscale).
Grayscale on Opera and Safari
Opera and Safari browsers do not support CSS grayscale filters so these browsers must be treated separately just like IE10+. Only these browsers can be fixed using JS solution which has been kindly provided by James Padolsey
That’s all about my cross-browser grayscale image solution setup. You can check out the demo or download the source. For those of you who want to get into more details, I have explained the magic behind the functions.js file, so that you could tweak the code as you need.
This function getBrowser() checks the browser user agent and after that adds corresponding class to the <body> tag – this way we can target browser with CSS or fire JS functions only on those browsers that we want (Except IE11 because of the new user-agent)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Detection function to tell what kind of browser is used
After we have created a way to tell what kind of browser is used by the user, we can start to target Grayscale image solutions with JS to the browsers that need it. I will start with Opera and Safari
If you have any further questions, suggestions about cross-browser grayscale image example using CSS3 + JS, feel free to write them below or contact me personally.
Nhận xét
Đăng nhận xét