Search code examples
javascriptimagetextkeyboard

Change whats on a page with keyboard (JS) (work with images)


So I was messing around with JS, and I made something that when I press a key it displays that letter. so if I were to press A on the keyboard, KeyA appears on the page, but I was wondering if it would be possible to make a image appear when I pressed A instead. Thanks in advance <3 (also what I have is in the code snippet)

const log = document.getElementById('log');

document.addEventListener('keypress', logKey);

function logKey(e) {
  log.textContent += ` ${e.code}`;
}

  function logKey(a) {
  log.textContent += ` ${a.code}`;
}

  function logKey(a) {
  log.textContent += ` ${a.code}`;
}

  function logKey(q) {
  log.textContent += ` ${q.code}`;
}

  function logKey(w) {
  log.textContent += ` ${w.code}`;
}

  function logKey(r) {
  log.textContent += ` ${r.code}`;
}

  function logKey(t) {
  log.textContent += ` ${t.code}`;
}

  function logKey(y) {
  log.textContent += ` ${y.code}`;
}
  function logKey(u) {
  log.textContent += ` ${u.code}`;
}
  function logKey(i) {
  log.textContent += ` ${i.code}`;
}
  function logKey(o) {
  log.textContent += ` ${o.code}`;
}
  function logKey(p) {
  log.textContent += ` ${p.code}`;
}
  function logKey(s) {
  log.textContent += ` ${s.code}`;
}
  function logKey(d) {
  log.textContent += ` ${d.code}`;
}
  function logKey(f) {
  log.textContent += ` ${f.code}`;
}
  function logKey(g) {
  log.textContent += ` ${g.code}`;
}

  function logKey(h) {
  log.textContent += ` ${h.code}`;
}
  function logKey(j) {
  log.textContent += ` ${j.code}`;
}

  function logKey(k) {
  log.textContent += ` ${k.code}`;
}
  function logKey(l) {
  log.textContent += ` ${l.code}`;
}
  function logKey(z) {
  log.textContent += ` ${z.code}`;
}
  function logKey(x) {
  log.textContent += ` ${x.code}`;
}
  function logKey(c) {
  log.textContent += ` ${c.code}`;
}
  function logKey(v) {
  log.textContent += ` ${v.code}`;
}
  function logKey(b) {
  log.textContent += ` ${b.code}`;
}
  function logKey(n) {
  log.textContent += ` ${n.code}`;
}
  function logKey(m) {
  log.textContent += ` ${m.code}`;
}
<p id="log"></p>


Solution

  • Just use a div instead of a

    and append dynamically generated images to it. Also don't redeclare your function each time it is pointless. Use a switch/case instead and check for keycodes :

    let div = document.getElementById("img");
    window.onkeypress = function(e) {
      switch(e.code) {
        //I just did the letter A but you get the idea
        case "KeyA":
          let img = document.createElement("img");
          img.src = "https://etc.usf.edu/presentations/extras/letters/fridge_magnets/red/11/A-300.png"
          img.style = "width:70px;height:100px;"
          div.appendChild(img)
          break;
      }
    }
    <div id="img"></div>