I feel I should point out that this can be done purely with CSS. ThisAlong with removing the need for javascript, this also has the benefit of fixing that "one minor defect".
Here's some explanation of what is going on here.
In the CSS, the lines about transition
(with and without browser prefixes), handle the transition of the default image to the hover image, giving it the fade effect.
To have this happen smoothly on the first time they're hovered, I've added the hover images to the dom to pre-load them so that they will already be loaded and cached in the elements with the .imgpl
class on them. These are hidden with CSS--they only serve to load the hover images. doing this is optional, but I feel it gives a better user experience. Without it, the browser has to load the image the first time it is hovered, which leads to a delay in the display.
The default image is defined as the background image,
.img1{background:url("http://www.placehold.it/350x150") no-repeat;}
And the hover images are defined with the :hover
pseudo class:
.img1:hover{background:url("http://www.placehold.it/351x151")no-repeat;}
Run the snippet below to see it work:.