I am trying to change the background image of a div on hover with jQuery. This is what I came up so far, however, it's not working:
html
<div class="logo"></div>
css
.logo {
width: 300px;
height: 100px;
background: url('http://placehold.it/300x100/ffffff/000000.png&text=first') no-repeat center top;
}
js
$('.logo').hover(
function(){
$(this).animate({backgroundImage: 'http://placehold.it/300x100/ffffff/000000.png&text=second'},'fast');
},
function(){
$(this).animate({backgroundImage: 'http://placehold.it/300x100/ffffff/000000.png&text=first'},'fast');
});
jsfiddle here: http://jsfiddle.net/26j6P/1/
What am I doing wrong? If I animate the background color, it works just fine...
You can't use jQuery's animate with images - it just doesn't work.
Use plain css, like this...
http://jsfiddle.net/26j6P/9/
Here's the css...
.logo {
width: 300px;
height: 100px;
background: url('http://placehold.it/300x100/ffffff/000000.png&text=first') no-repeat center top;
transition: 0.5s;
}
.logo:hover {
background-image: url('http://placehold.it/300x100/ffffff/000000.png&text=second');
}
You cannot animate non numerical properties with .animate()
DEMO
$('.logo').hover(
function () {
$(this).animate({
opacity: 0
}, 'fast', function () {
$(this)
.css({
'background-image': 'url(http://placehold.it/300x100/ffffff/000000.png&text=second)'
})
.animate({
opacity: 1
});
});
},
function () {
$(this).animate({
opacity: 0
}, 'fast', function () {
$(this)
.css({
'background-image': 'url(http://placehold.it/300x100/ffffff/000000.png&text=first)'
})
.animate({
opacity: 1
});
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With