stoping a javascript code on pressing shift key

85 views Asked by At

I am using this JavaScript code to move some clouds now I need to check if user pressed shift key - when they do, it stop the animation of this cloud

The code I'm using to move is:

<script language="javascript">

  function StartMove() {
    var cssBGImage=new Image();
    cssBGImage.src="path to your image.jpg";

    window.cssMaxWidth=cssBGImage.width;
    window.cssXPos=0;
    setInterval("MoveBackGround()",50);
  }

  function MoveBackGround () {
    window.cssXPos=window.cssXPos+1;
    if (window.cssXPos>=window.cssMaxWidth) {
      window.cssXPos=0;
    }
    toMove=document.getElementById("scroller");
    toMove.style.backgroundPosition=window.cssXPos+"px 0px";
  }
</script>

Something like this code. Note this one doesn't work with me

function GetShiftState (event) {
  if (event.shiftKey)
  {
    document.getElementById("myimg").clearTimeout(t);
  }
}
1

There are 1 answers

0
jasonscript On

You need to keep track of the name of the interval

See this relevant example at MDN

var global_cloudInterval;

function StartMove() {
    var cssBGImage=new Image();
    cssBGImage.src="path to your image.jpg";

    window.cssMaxWidth=cssBGImage.width;
    window.cssXPos=0;

    // Keep track of the interval using a global variable
    // also, don't need to wrap MoveBackGround in quotes
    global_cloudInterval = setInterval(MoveBackGround, 50);
}

function MoveBackGround () {
    window.cssXPos=window.cssXPos+1;
    if (window.cssXPos>=window.cssMaxWidth) {
        window.cssXPos=0;
    }
    toMove=document.getElementById("scroller");
    toMove.style.backgroundPosition=window.cssXPos+"px 0px";
}

function GetShiftState (event){
    if (event.shiftKey){
        // now clear the interval using the global variable
        clearInterval(global_cloudInterval);
    }
}