CSS grayscale with animation

user1660309 picture user1660309 · Sep 10, 2012 · Viewed 14.1k times · Source

i have some css for changing my image into grayscale (with some svg for firefox)

img.grayscale{
            filter: grayscale(100%);
            -webkit-filter: grayscale(100%); 
            -moz-filter: grayscale(100%);
            -ms-filter: grayscale(100%); 
            -o-filter: grayscale(100%);
            filter: url(desaturate.svg#greyscale);
            filter: gray;
            -webkit-filter: grayscale(1);
        }

but now i want animation on hover for changing the value of the grayscale to 0.

I have this code but it doesn't do anything (on chrome of course), i have no idea why it doesn't animate at all.

<script type="text/javascript">
        $(".grayscale").hover(
            function () {
                $(this).animate({
                    '-webkit-filter': 'grayscale('0'%)'
                }, 300);
            }
        );
    </script>

I think it's possible to animate the % from 100% to 0%, isn't it?

Edit : i'm trying to do for all browsers, not only chrome but i do my tests on chrome that's why i'm not changing all the properties. I think when i'll found the answer for chrome i'll can do the same for the other browers :)

Answer

wavetree picture wavetree · Sep 10, 2012

Why use animate() at all? You're already only animating for webkit, so why not use the transition property and classes to trigger the animation? Like this:

img {
  -webkit-transition: all 300ms;
}

img.grayscale {
  -webkit-filter: grayscale(1);
}

And then just remove the class by calling

$('img.grayscale').removeClass('grayscale');

Note: I don't know what the specific property is to just animate just the grayscale, but if you're not doing any other transitions on the element, transitioning "all" works just fine.