Tuesday, December 22, 2009

Gray Scale images in all Browsers

Its been a while since I blogged on anything.
Today I came across a post at forums.asp.net: change color image to gray scale

GrayScale - Converts the colors of the object to 256 shades of gray.
An example will be

Since GrayScale filter is a filter present in the Internet Explorer,
we can achieve this result in IE simply by using the css property
 filter: gray;
 -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)";
 filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);
Here the second method is more advanced and must have Internet Explorer 5.5 or later to work properly.

There are number of filters in IE apart from GrayScale. Here are some lists

1. Static filters by MSDN
2. CSS Visual Filters
3. IE Multimedia filters reference

This is the case with Internet Explorer.
Now the big question.

Why does not the GrayScale filter work with browsers like Chrome, Firefox and Safari?
Simple. The filter is specific to IE only.

While I was searching through the internet for a good solution, I found this at SO
There I discovered a wonderful javascript coder named James Padolsey who is just 19!

Copied his GrayScale.js which according to James Padolsey is

Grayscale.js is an experimental attempt to emulate Microsoft's
proprietary 'grayscale' filter (available in most IE versions).

And it worked like a charm.

So here are the steps involved in achieving the hover effect

1. Grab the GrayScale.js from James Padolsey's site. (The link is here)

2. Add refernce to jQuery. Please note that jQuery is not required for grayscale.js - it's only used for this demo
Its better to refer jQuery like this (Read Dave Ward ka Encosia on this topic)
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="/js/jQuery.min.js"></script>
3. Add a small javascript snippet like this
   }, function(){
4. Assign the class="greyonhover" for the image you want to implement grayscale effect onhover
<img class="greyonhover" src="images/naveenj-thumb.jpg" />

This is all you have to do to achieve greying effect on hover. Download Source Code(9k)