Search code examples
javascriptjquerycssbackground-position

background-position change in increments with jQuery


I'm trying to workout an efficient way to cycle though in 25% increments the background image of an element, but when it gets to 100% it would go back to 0% on the next increment.

I can do something like this:

var currentPos = $('.ele1').css('background-position');
var elementPositions = currentPos.split(' ');

var x = Number(elementPositions[0].replace(/[^0-9-]/g, ''));
//var y = Number(elementPositions[1].replace(/[^0-9-]/g, ''));

// only want to do the x axis
x = (x == 100) ? 0 : x += 25;

$('.ele1').css('background-position', x + "%" + " 0");

But I don't like the fact I have to call the element twice. Is there a more efficient way to increment a % with jQuery and have it reset back to 0% after 100%?

I did think to do it with CSS .classes. But I don't really want to be restricted to what's in my style sheet.


Solution

  • You can pass a callback function to jQuery's .css() method:

    $('.ele1').css('background-position', function (i, value) {
        var x = parseInt(value, 10);
        return (x == 100 ? 0 : x + 25) + "%" + " 0";
    });
    

    If you're calling this from within a loop/timer/event/whatever, you should cache the $('.ele1') object.