$('img').hover(function(){ $(this).toggleClass("grayscale") }); 
 body{ padding: 50px 10px; } img{ border: 10px solid #ccc; box-shadow: 0px 0px 1px #555; } img.grayscale{ filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale"); /* Firefox 10+, Firefox on Android */ filter: gray; /* IE6-9 */ -webkit-filter: grayscale(100%); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div> <a href="#" title=""><img class="grayscale" src="http://farm9.staticflickr.com/8380/8464961316_bff336e8b1.jpg" width="480" height="246" alt=""></a> </div> 

I’ve been looking for this effect for a long time and really cross-browser, but how on js to make the image be black and white and with hover it becomes color? Or still use two images?

  • you can use a picture - the most cross-browser method - Grundy
  • as I was waiting for this answer - I thought so - make the answer - I will make it better - but I found the solution - I check it on all devices - user33274
  • @LenovoID: Why do you impose hovers with jQuery? Is there a standard CSS selector img:hover { } ? - user200141
  • by the fact that it is cross-browser - and it is not possible to add a class element to a hover - user33274

1 answer 1

You can do it easier:

 img:hover{ filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale"); /* Firefox 10+, Firefox on Android */ filter: gray; /* IE6-9 */ -webkit-filter: grayscale(100%); } 
  • And why add a class? Do you want to add effect to certain images? You after all all the same in jquery select the selector (img). In css, you can set the same selector for all images or for specific ones. And this is a cross-browser. And it works faster than through jquery - gam1et22
  • I already wrote it seems - it is necessary to make a color from black and white - for example, I applied a filter - but how to cancel it on a hover ?? - user33274
  • Sorry, did not notice. So let img initially have -webkit-filter: grayscale (100%), and on: hover it will be the value of none or grayscale (0%). It seems to work. I am writing from the phone, I can not check it - gam1et22
  • I did it - and unfortunately I can’t cancel it, I wrote: hover: filter (none); and so: hover: filter (0%); and as soon as I didn’t do it and the best thing is hover on jquery - user33274
  • Indeed, nothing works on IE - gam1et22