Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change sprite position dynamically?

this is a sprite i found

enter image description here

.common-spinner.common-spinner-40x55 {
    height: 55px;
    width: 40px;
}

.common-spinner {
    background: url("images/loading-sprite.png") no-repeat scroll 100% 100% transparent;
}

<div class="loading">
<div class="common-spinner common-spinner-40x55" style="background-position: 0px 0px;"></div>
</div>

any idea how to build the loading animation from this? i tried to change position using a for loop like

for(i=0; i<=720;) {
    $('.common-spinner').css('background-position', '-'+i+'px 0px');
    i=i+20;
}

but i can not see any animation maybe because its going too fast?

any idea how to do this?

Regards

Ive added the code to jsfiddle with Erik Hesselink solution

http://jsfiddle.net/X7tGb/

like image 935
Gihan Lasita Avatar asked Dec 05 '11 18:12

Gihan Lasita


1 Answers

To actually see the animation, you have to leave the Javascript execution thread. This can be done by using timeouts. Something like:

function setBgPosition (px)
{
  return function ()
  {
    $('.common-spinner').css('background-position', '-' + px + 'px 0px');
    if (px < 720) setTimeout(setBgPosition(px + 20), 100);
  }
}

setTimeout(setBgPosition(0), 100);
like image 121
Erik Hesselink Avatar answered Oct 05 '22 22:10

Erik Hesselink