Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery to change (with fade animation) background image of div on hover

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...

like image 629
noname Avatar asked Sep 12 '13 08:09

noname


3 Answers

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');
}
like image 79
Reinstate Monica Cellio Avatar answered Nov 04 '22 09:11

Reinstate Monica Cellio


You cannot animate non numerical properties with .animate()

like image 6
DGS Avatar answered Nov 04 '22 10:11

DGS


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
                });
        });
});
like image 4
Tushar Gupta - curioustushar Avatar answered Nov 04 '22 08:11

Tushar Gupta - curioustushar