Using jQuery to change the background position of a sprite in CSS for all elements

Tarek Shalaby picture Tarek Shalaby · Aug 20, 2012 · Viewed 7.5k times · Source

I have an image sprite that is the background of the main div, with a dozen links inside it. Instead of writing the values of the background-position in the CSS file for each link when it's hovered, I want to do it in jQuery so that the background-position y increases by 550px (the x position will remain the same).

The Markup:

<div class="compass">
    <a class="facebook" href="#">&nbsp;</a>
    <a class="twitter" href="#">&nbsp;</a>
    <a class="youtube" href="#">&nbsp;</a>
</div>

The CSS:

.compass {
    background-image: url('../images/compass.png');
    background-position: top;
    height: 550px;
    position: relative;
    width: 567px;
    margin: 0 auto;
}
.compass a{
    background-image: url('../images/compass.png');
    background-position: top;
    display: block;
    position: absolute;
}
a.facebook {
    height: 51px;
    width: 26px;
    left: 151px;
    top: 190px;
}

So the idea is to write a CSS rule style for each link indicating the x and y positions of the background image. Then, on hover, the y position would increase by 550px. On mouseout, it would go back to hot it was (a 550px decrease).

I've started the jQuery syntax but can't figure it out:

var originalPosition = obj.css('background-position');
$(".compass a").hover(
    function(){
        $(this).css('backgroundPosition', originalPosition + 550 + "px")
    },
    function(){
        $(this).css('backgroundPosition', "");
    }
)

Thank you all very much!

Answer

Fabr&#237;cio Matt&#233; picture Fabrício Matté · Aug 20, 2012

Edited to work in FF as well.

$(".compass a").hover(function() {
    var bgpos = $(this).css('backgroundPosition').split(' ');
    $(this).css('backgroundPosition', bgpos[0] + ' ' + (parseInt(bgpos[1],10)+550) + 'px');
}, function() {
    var bgpos = $(this).css('backgroundPosition').split(' ');
    $(this).css('backgroundPosition', bgpos[0] + ' ' + (parseInt(bgpos[1],10)-550) + 'px');
});

Fiddle

Credits to this answer for the FF hack.