Ask coding questions

← Back to all posts
HTML
srsly (30)

How would you do something like
if key "a" pressed
print("BLAH")
how would you do something like that in html

Answered by Coder100 (16791) [earned 5 cycles]
View Answer
Comments
hotnewtop
Coder100 (16791)

you will use js for this:

window.addEventListener("keydown", e => {
  if (e.key == "a") { alert("BLAH"); }
});
srsly (30)

@Coder100 How would i do
window.addEventListener("keydown", e => {
if (e.key == "a") { alert("BLAH"); }
}); and then if they would click a it would change the x or y position
(like can you give me a example)

Coder100 (16791)

i'm sorry change what
and click what @srsly

srsly (30)

@Coder100 so first we would do this:
window.addEventListener("keydown", e => {
if (e.key == "a") { alert("BLAH"); }
}); then I want to do if a is clicked on the keyboard it will change the x or y position of an image how would i do that?

Coder100 (16791)

i would like to say that I already gave you the code for pressing the a key remember?

here we go:

let img = document.querySelector("img");
window.addEventListener("keydown", e => {
  if (e.key == "a") {
    let newLeft = parseInt(img.style.left) - 3;
    img.style.left = newLeft + "px";
  }
});

@srsly