Search code examples
jqueryjquery-animatebackground-position

Animate background not working as expected


I have done this sort of thing before, but it's not working for me now...

I have a container div, and a div inside with partly transparent image. When the user hovers over the container div I would like the background on that div to move 0px -56px. I have tried this using animate like I usually do, its not working. Initially my old script would not work in 1.6 so Im back on 1.4.2, its making no difference, so maybe my code is just rubbish...

$('.trans_bg').css({"background-position":"0 0"});
$('.trans_bg').hover(
function() {
    $(this).animate({backgroundPosition: "(0px -56px)"},{duration:300}); 
},
function(){
    $(this).animate({backgroundPosition: "(0px 0px)"},{duration:300});
})

Any ideas?


Solution

  • Your code is almost correct, just remove parentheses when setting the new position:

    $('.trans_bg').css({ backgroundPosition: "0 0" });
    $('.trans_bg').hover(function() {
        $(this).animate({ backgroundPosition: "0px -56px"}, 300);
    }, function() {
        $(this).animate({ backgroundPosition: "0px 0px"}, 300);
    });
    

    But unfortunatelly, jQuery can't animate backgroundPosition natively.

    But there is a great plugin to do it: Background-Position Animation Plugin.

    Grab it to your project so the typed code just starts working!