Search code examples
javascriptkeypresskeydown

how to code multiple keys on keydown? (javascript)


I'm trying to have each key, correspond to different images when pressed. (Ex: When "A" is pressed = image1 appears, When "S" is pressed = image2 appears, and so on.)

I was able to get the "S" Key to work, but not the A. I'm trying to do this for the whole row on the keyboard ("A","S","D","F","G","H","J","K","L")

*PS. Im still a beginner :)

This is my code:

<img src="images/giphy.gif" width="800" height="400" alt=""/>

<script>
  document.addEventListener("keydown", keyDownBody, false);

  function keyDownBody(e) {
    var keyCode = e.keyCode;
    if(keyCode==65) {
      myFunction();
    }
  }

function myFunction() {
var x = document.createElement("IMG");
x.setAttribute("src", "images/giphy1.gif")
x.setAttribute("width", "800");
x.setAttribute("height", "400");
x.setAttribute("alt", "The Pulpit Rock");
document.body.appendChild(x);
}

function keyDownBody(e) {
    var keyCode = e.keyCode;
    if(keyCode==83) {
      myFunction();
    }
  }

function myFunction() {
var x = document.createElement("IMG");
x.setAttribute("src", "images/sun.gif")
x.setAttribute("width", "800");
x.setAttribute("height", "400");
x.setAttribute("alt", "The Pulpit Rock");
document.body.appendChild(x);
}
</script>

Solution

  • You have declared the same function multiple times. You could merge them to make it work, and also make your code more readable. An example:

    document.addEventListener("keydown", keyDownBody, false);
    
    function keyDownBody(e) {
      var keyCode = e.keyCode;
      switch (keyCode) {
        case 65:
            loadImage("images/giphy1.gif", "The Pulpit Rock");
            break;
        case 83:
            loadImage("images/sun.gif", "The Pulpit Rock");
            break;
    
        // Etc.
      }
    }
    
    function loadImage(uri, alt) {
        var x = document.createElement("IMG");
        x.setAttribute("src", uri)
        x.setAttribute("width", "800");
        x.setAttribute("height", "400");
        x.setAttribute("alt", alt);
        document.body.appendChild(x);
    }
    

    This way you can add as many keys as you wish.

    Alternatively, you could load the images dynamically if you put them in an array:

    var images = [{
          uri: 'images/giphy1.gif',
          alt: 'A',
        }, {
          uri: 'images/sun.gif',
          alt: 'Some text',
        }, 
        // Etc.
    ];
    
    function keyDownBody(e) {
      var keyCode = e.keyCode;
    
      var index = keyCode - 65;
      if (typeof images[index] !== 'undefined')
      {
        var image = images[index];
        loadImage(image.uri, image.alt);
      }
    }