0

This doesn't animate as I expect it would, why doesn't it animate?

HTML

<div id='menuI'></div>

CSS

#menuI {
    height: 100px;
    width: 100px;
    background:url('https://www.teledynedalsa.com/images/semi/STA1600_2_200w.jpg') 0px 0px;
    text-align:justify;
}

JavaScript

$(document).ready(function(){
    $('#menuI').mouseenter(function(){
        $('#menuI').stop();
            $('#menuI').animate({
                backgroundPosition: '0px 100px'
            }); 
        });
    $('#menuI').mouseleave(function(){
        $('#menuI').stop();
        $('#menuI').animate({
            backgroundPosition: '0px 0px'
        }); 
    }); 
});
Kara
  • 6,115
  • 16
  • 50
  • 57

2 Answers2

2

As showdev said you need a jQuery plugin to achieve this. However you can also consider using transitions instead since it is very well suited for this.

The following css will cause the same

#menuI {
    height:100px;
    width:100px;
    background:url('https://www.teledynedalsa.com/images/semi/STA1600_2_200w.jpg') 0px 0px;
    transition: background linear 0.4s; //Add vendor prefixed versions
    text-align:justify;
}

#menuI:hover {
    background-position: 0px 100px;
}

Example: http://jsfiddle.net/9fCnN/

Hugo Tunius
  • 2,869
  • 24
  • 32
  • Nice alternative to using jQuery. Re: "vendor prefixed versions" for cross-browser support: http://jsfiddle.net/9fCnN/1/ – showdev Dec 19 '13 at 00:32
1

I believe a plugin is required to animate "backgroundPosition".

I had success using the background-position-y property:

$(document).ready(function () {
    $('#menuI').mouseenter(function () {
       $(this).stop().animate({'background-position-y':'100px'});
     });
    $('#menuI').mouseleave(function () {
        $(this).stop().animate({'background-position-y':'0px'});
    });
});

http://jsfiddle.net/Ub7aN/1/

Edit:

Unfortunately, this does not seem to work in Firefox.

See these posts:
JQuery Animate Background Image on Y-axis
Animate background position y in Firefox with Jquery

Community
  • 1
  • 1
showdev
  • 28,454
  • 37
  • 55
  • 73
  • It doesn't work in the jsfidde or on your own page? What goes wrong? Which version of jQuery? – showdev Dec 19 '13 at 00:33
  • Works in Chrome though, weirdness; I'd like this to be supported across browsers. I might just have to write my own loop to animate it for cross browser support :O – user3117081 Dec 19 '13 at 00:36
  • There are some other posts here on SO dealing with animation of background position. You might want to check them out. Some interesting methods. Also, CSS transitions are pretty sweet (see answer by @HugoTunius). – showdev Dec 19 '13 at 00:39