title: Animation Array in JavaScript
body: <p>I've come up with this little animation that uses images in an array, but it's sloppy. What I'd really like is to modularize it so that I can use <strong>multiple instances of the same function to animate different arrays depending on which key is pressed</strong>. Also, I'd like to get it so that the <strong>animation stops when the key is released</strong>, if possible. I realize that calling all of those variables globally is a big no-no, but I have no idea how to make it work otherwise! Last but not least, I'd like to figure out how to get that <strong>last bit of inline script over to the external file</strong> and have it still work correctly. Any help would be much appreciated! But please note, I'm a novice with JavaScript, so <strong>please try to be as specific/detailed as possible</strong> so I can learn from your wisdom! Thank you!</p>
  
  <p>I've created a <a href="http://jsfiddle.net/ghQwF/2/" rel="nofollow">jsfiddle</a>.</p>
  
  <p>HTML:</p>
  
  <pre><code>&lt;div id="wrapper"&gt;
  &lt;span id="jajo"&gt;&lt;img id="my_img" src="jajo.png" /&gt;&lt;/span&gt;
  &lt;script&gt;element = document.getElementById("jajo"); &lt;/script&gt;
  &lt;/div&gt;&lt;!--wrapper--&gt;
  </code></pre>
  
  <p>JavaScript:</p>
  
  <pre><code>var i = 0;
  var element;
  var waveArray = ["wave0.png","wave1.png","wave2.png","wave3.png","wave4.png","wave5.png"];
  var jumpArray = ["jump0.png","jump1.png","jump2.png","jump3.png","jump4.png","jump5.png"];
  var foodArray = ["food0.png","food1.png","food2.png","food3.png","food4.png","food5.png"];
  
  document.onkeydown = function(event) {
  var keyPress = String.fromCharCode(event.keyCode);
  
  if(keyPress == "W") { // if "w" is pressed, display wave animation
      increment ();
  
      document.onkeyup = function(event) { // if "w" is released, display default image
          document.getElementById("jajo").innerHTML= "&lt;img alt='Jajo' src='jajo.png'&gt;";
      }
  } else if(keyPress == "A") { // if "a" is pressed, display jump animation
  } else if(keyPress == "S") { // if "s" is pressed, display food animation
  }
  }
  
  function increment (){
  i++;
  if(i &gt; (waveArray.length - 1)){
      i = 0;
  }
  setTimeout(animation,1000/30);
  }
  
  
  function animation() {
  var img = '&lt;img src="' + waveArray[i] + '" alt="Jajo" /&gt;';
  element.innerHTML = img;
  setTimeout(increment, 2000/30);
  }
  </code></pre>