views:

55

answers:

3

So I have working code that animates a BG image via a plugin. This is a general solution though where each element in the class has the same BG image; I'm using a sprite with a unique image for each column of my navigation bar. THe code is thusly:

$('#nav a')
.mouseover(function(){
    $(this).stop().animate(
        {backgroundPosition:"(0 -250px)"}, 
        {duration:500})
    })
.mouseout(function(){
    $(this).stop().animate(
        {backgroundPosition:"(0 0)"}, 
        {duration:500})
    })

This works great, so I can set a Y-offset for each element, but each link has it's own x-offset that won't change/be animated at all. Example CSS:

li.downloads a {
    background:url(img/navsprite.png) repeat -318px -9px;
}

I want to roll the -318px -9px to something like -318px 200px, but for another element I'd want to change -482px -9px to -482px 200px. Only the Y-offset should change, but I don't know the syntax of jQuery well enough to pull that value from the CSS of $(this) element and put it into the animate parameters. Thanks!

+4  A: 

You can get the background position like this:

$(this).css("background-position");

You can get both values in an array like this:

var bgpos = $(this).css("background-position").split(" ");

Which allows you to access both values with bgpos[0] and bgpos[1].

Jonathan Sampson
And are both the X and Y attributes further selectable? Ideally what I'd want was to say "Change to BackgrounPosition:($x -200px)" or something similar
Alex Mcp
@Alex: See my updated text. You could refer to both via array-entries following a split on the value.
Jonathan Sampson
at that point, I think you need to use regex to get your values
Mike
Awesome. Thanks bunches.
Alex Mcp
@Mike: Not necessarily. Note that I simply split the string into two parts, and accessed both values via indexes in the resulting array.
Jonathan Sampson
A: 

There is a css property background-position-x. This is only available in IE however, so is probably not a valid solution for your problem.
jQuery does support relative animations by specifying f.e. +=50px;
No idea if it works, but you could try the following code:

$('#nav a')
.mouseover(function(){
    $(this).stop().animate(
        {backgroundPosition:"(+=0 -250px)"}, 
        {duration:500})
    })
.mouseout(function(){
    $(this).stop().animate(
        {backgroundPosition:"(+=0 0)"}, 
        {duration:500})
    })
Jasper De Bruijn
A: 
jQuery.fn.getBackgroundxPosition = function(val) {
    var position = $(this).css('background-position');
    var position_array=val.split(' ');
    var x_pos = position_array[0];

    if(typeof(position) === 'undefined'){ //IE fix
        x_pos = $(this).css('background-position-x');
    }
return x_pos;
};

I think this will work (not tested)

Tim