I'm looking to enhance my logo listing with a hover effect that switches the logo from color to black and white. Here's the current markup I have:
var sourceToggle = function () {
var $this = $(this);
var newSource = $this.data('hover');
$this.data('hover', $this.attr('src'));
$this.attr('src', newSource);
}
$(function() {
$('img[data-hover]').each(function() {
new Image().src = $(this).data('hover');
}).hover(sourceToggle, sourceToggle);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="url">
<img src="http://lorempixel.com/200/200/sports/1/" data-hover="http://lorempixel.com/g/200/200/sports/1/">
</a>
This code is currently functional, but I'm wondering if there are ways to optimize it or make it shorter.
Additionally, I would like to explore options for preloading the hover image to prevent any flickering when it's not loading fast enough.