0

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.

james
  • 1,031
  • 1
  • 15
  • 31
  • Why do you want this to be more efficient? Is it affecting user experience? Or just want to have a more elegant solution? – Kaizen Programmer Jan 29 '13 at 19:23
  • Its for a sprite solution for a game. So I really need to get it as efficient as possible. But the game doesn't need a complex sprite animation framework. Just something like the above, but better . – james Jan 29 '13 at 19:25
  • `parseInt($('.ele1').css('background-position-x'), 10)` will give you the x position as an integer. No need for the split/replace/etc. – glomad Jan 29 '13 at 19:33
  • is background-position-x cross browser compatible? – james Jan 29 '13 at 19:37
  • 1
    Also: if you search stackoverflow for 'jquery sprite animation', you will find a lot of people doing very similar things, and maybe some pointers on efficiency. – glomad Jan 29 '13 at 19:37
  • jQuery provides a cross-browser compatibility layer for CSS properties, so yes. But as noted in @JosephSilber's answer, just doing `parseInt()` on the background-position will work too because parseInt will discard anything after the first integer it finds in the string. – glomad Jan 29 '13 at 19:40

1 Answers1

3

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.

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292