Search code examples
javascriptjquerysprite-sheet

Run left / right sprite animation by click


I have problem with this sprite animation. sprite-sheet The script don't change the correct animation, and the speed increases each time you click in the same direction.

<div id="coordinates">MOUSE XY</div>    
<div id="map" style="width:960px; height:80px; background-color:black; ">   
 <div id="player"></div>  
</div>

Javascript and Jquery

<style> #player{background-image:url('girl_60x60.png'); 
    width:60px; height:60px; position:relative; 
    z-index:12; left:465px;}</style>

<script type="text/javascript"> 
 // click event 
 $('#map').click(function(e) { 
  // take coordinates
  var posX = e.pageX ;
  var posY = e.pageY;
  //print X e Y
  $('#coordinates').html("X: " + posX + " Y: " + posY); 

  if (posX <= 480) {   //Check the click relative to the center.
   setInterval('ani_left()',100); //left animation                          
  } else {              
   setInterval('ani_right()',100); //right animation
  }
}); 

var frame = 1;

// Right animation
function ani_right() {
 var left = 60 * frame;  //next frame every 60px
 var top = 0;
 $('#player').css('backgroundPosition','-'+left+'px -'+top+'px');
 frame++;
}
// left animation
function ani_left() {
 var left = 60 * frame;
 var top = 60;   //second row of frames
 $('#player').css('backgroundPosition','-'+left+'px -'+top+'px');
 frame++;
}
</script>

Solution

  • You should stop the execution of previous setInterval with clearInterval(idInterval).

    I reccomend you to use setInterval(funcName,100) and not setInterval('funcName()',100);

    var idInt = -1; // add this
     // click event 
     $('#map').click(function(e) { 
         if(idInt != -1) 
             clearInterval(idInt); // add this 
    /* .. CUT .. */
    
      if (posX <= 480) {   //Check the click relative to the center.
          idInt = setInterval(ani_left,100); //left animation                          
      } else {              
          idInt = setInterval(ani_right,100); //right animation
      }
    }); 
    
    /* cut */
    

    Fiddle here