views:

23

answers:

1

I'm trying to do a very very simple mouseover that animates a change in background position.

js

$('li.services_w')
    .css( {backgroundPosition: "0px 0px"} )
    .mouseover(function(){
        $(this).stop().animate({backgroundPosition:"(0px -35px)"}, {duration:500})
    })
    .mouseout(function(){
        $(this).stop().animate({backgroundPosition:"(0px 0px)"}, {duration:200, complete:function(){
            $(this).css({backgroundPosition: "0px 0px"})
        }})
    });

Except everytime I run this code, the background always returns background-position: 0 50% as the outcome of the mouseover. No matter what I change those numbers too! I assure you this is the only javascript I am using.

css

.services_w {
  height: 35px;
  overflow:hidden;
  background: url("../img/services_w.jpg") repeat 0px 0px;
}
.services_w:hover {
  background-position: 0px -35px;
}

html

<div class="grid_10 nav">
  <ul class="lavaLamp">
    <li class="current"><a href="index.html">home</a></li>
    <li class="services_w"><a href="services.html">services</a></li>
    ...
+1  A: 

Remove the extra "(....)" that's invalid CSS, like this:

$('li.services_w')
    .css( {backgroundPosition: "0px 0px"} )
    .mouseover(function(){
        $(this).stop().animate({backgroundPosition:"0px -35px"}, {duration:500})
    })
    .mouseout(function(){
        $(this).stop().animate({backgroundPosition:"0px 0px"}, {duration:200, complete:function(){
            $(this).css({backgroundPosition: "0px 0px"})
        }})
    });

Or a bit cleaner using .hover() and specifying the duration directly:

$('li.services_w').css( {backgroundPosition: "0px 0px"} )
    .hover(function(){
        $(this).stop(true, true).animate({backgroundPosition:"0px -35px"}, 500);
    }, function(){
        $(this).stop(true, true).animate({backgroundPosition:"0px 0px"}, 200);
    });
Nick Craver
holy crap you have a lot of points.
Trip
@Trip - People with *way* more than me :) http://stackoverflow.com/users
Nick Craver
Out of speculation, that second cleaner version doesn't actually animate it. somehow the animate gets deprecated by the mouseover and its an instant change.
Trip
@Trip - You can adjust the `.stop()` parameters depending on the exact behavior you want, the first tells it whether to clear the queue, the second tells it whether to finish the first animation, so you may just want `.stop(true)` instead of `.stop(true, true)`.
Nick Craver
I thought of that but it wasn't it. Its quirky because if I animate opacity or any other attribute it works as expected. But background attribute is not animated.
Trip
@Trip - You sure this code isn't running twice or anything? Would love to see the actual page you're having issues on, something out of the ordinary going on.
Nick Craver