JSFiddle - React, Tailwind, and code Playground
http://stackoverflow.com/questions/16316153/jquery-to-animate-background-on-hover
by lalatino
HTML
<span class="bgspan">
<a href="#"> link 1 </a>
</span>
<span class="bgspan">
<a href="#"> link 2 </a>
</span>
<span class="bgspan">
<a href="#"> link 3 </a>
</span>
CSS
.bgspan {
position: relative !important;
border:1px solid red;
font-size:3em;
margin-right:1em;
}
.bgspan a {
z-index: +1;
}
.bgimage {
background:url('/path/img1.jpg') no-repeat top left;
z-index:-1;
opacity:1;
}
.bgimagehover {
background:url('/path/img2.jpg') no-repeat top center;
z-index:-1;
opacity:0;
}
JavaScript
$(document).ready(function () {
$('.bgspan').each(function () {
var tmp = $('<span/>');
//tmp.css({ border:'5px solid yellow'} );
tmp.css({ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 });
tmp.addClass('bgimage');
tmp.appendTo(this);
var tmp = $('<span/>');
//tmp.css({ border:'5px solid orange'} );
tmp.css({ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0 });
tmp.addClass('bgimagehover');
tmp.appendTo(this);
});
$('.bgspan a').hover(function () {
$(this).parent().find('.bgimage').stop().animate(
{opacity:0, queue: false,duration:500}
);
$(this).parent().find('.bgimagehover').stop().animate(
{opacity:1, queue: false,duration:500}
);
}, function () {
$(this).parent().find('.bgimage').stop().animate(
{opacity:1, queue: false,duration:500}
);
$(this).parent().find('.bgimagehover').stop().animate(
{opacity:0, queue: false,duration:500}
);
});
});