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'
        }); 
    }); 
});

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Nice alternative to using jQuery. Re: "vendor prefixed versions" for cross-browser support: jsfiddle.net/9fCnN/1
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

3 Comments

It doesn't work in the jsfidde or on your own page? What goes wrong? Which version of jQuery?
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
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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.