views:

182

answers:

1

Hi guys,

I've created an image which is basically a CSS sprite of 3 images together. It's size is 278x123 so they are basically 3 images of 278x41.

What I am trying to do is to make an animation of that by changing the background position.

I've tried many things, one of my not very working solution is the following:

    var $slogan = $('#header h2 span');
$slogan.css({backgroundPosition: '0px 0px'});
function slogan_animation() {
    if ($slogan.css('background-position') == '0px 0px') {
        $slogan.fadeIn('slow').css('background-position', '0px -41px').fadeOut('slow');
    }
    else if ($slogan.css('background-position') == '0px -41px') {
        $slogan.fadeIn('slow').css('background-position', '0px -82px').fadeOut('slow');
    }
    else if ($slogan.css('background-position') == '0px -82px') {
        $slogan.fadeIn('slow').css('background-position', '0px 0px').fadeOut('slow');
    }
}
setInterval(slogan_animation, 2000);

Any ideas how could I do that?

Basically I just need to: - set my background position to "0px 0px", then move it to "0px -41px", then "0px -82px" and then loop it again from "0px 0px". It would be also great to have fadeIn() effect between those.

Any ideas?

Thank you.

+1  A: 

The background-position style is a composite style, so when you read it, it might not give the result that you expect. Also, the result may differ between browers.

Try using a variable to keep track of the position instead of reading it from the style. Set the position before you start the fade in:

$(function(){

  var $slogan = $('#header h2 span');
  var offset = 0;

  window.setInterval(function(){
    $slogan.css('background-position', '0 -'+offset+'px')
    .fadeIn('slow')
    .fadeOut('slow');
    offset = (offset + 41) % 123;
  }, 2000);

});
Guffa