Using jquery, I am trying to get a background image to fade into a different one when you mouse over it, and fade out when you take your mouse off. I have tried countless solutions over the last few hours, and can’t seem to find one that applies. Below is my css
.thumbnail span {
background: url('images/portfolio.png') no-repeat;
width: 298px;
height: 160px;
position: absolute;
top: 0;
left: 0;
margin-left:-2px;
cursor: pointer;
}
.thumbnail span .rollover {
background: url('images/portfolio_vignette.png') no-repeat;
}
and here is my JavaScript:
<script type="text/javascript">
$(document).ready(function(){
$(".rollover").css({'opacity':'0'});
$('.thumbnail span').hover(
function() {
$(this).find('.rollover').stop().fadeTo(500, 1);
},
function() {
$(this).find('.rollover').stop().fadeTo(500, 0);
}
)
});
</script>
Cheers guys!
Make sure to put a
divwrapper around your two images and attach the hover event to that. If you don’t, your hover will continuously trigger as the image disappears/appears.Here, I simply fade the last element out when hovering, and in when un-hovering. Of course, you could be more specific and act on
imgtags only, or on specific ID’s. The generic way is more useful as you never have to write the code again for another pair of images.HTML:
jQuery:
Example: http://jsfiddle.net/jtbowden/wQkWR/
Example using divs with background images: http://jsfiddle.net/jtbowden/wQkWR/1/