Michael
Michael

Reputation: 43

How can I use the keydown event in an if/else statement

I'm trying to make an online light bulb for my middle school science fair project and I want to add an "easter egg" where an alert pops up. I am trying to get it to activate when a certain key is pressed. This is the code I have so far:

HTML

<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8">
    <title>Light Bulb</title>
    <link href = "file.css" rel = "stylesheet">
  </head>
  <body>
    <button id = "light-switch">Turn on Light</button>
    <p id = "lightStatus">Light is off</p>
    <p id = "easterEgg"></p>
  </body>
  <script src="file.js"></script>
</html>

JS

let swt = document.querySelector("#light-switch");
let sta = document.querySelector("#lightStatus");
let egg = document.querySelector("#easterEgg");
let html = document.querySelector("html");

swt.addEventListener("click", updateSwt);

function updateSwt() {
  if(swt.textContent === "Turn on Light"){
    swt.textContent = "Turn off Light";
    swt.style.backgroundColor = "Yellow";
    console.log("on");
    sta.textContent = "Light is on";
  }
  else{
    swt.textContent = "Turn on Light";
    swt.style.backgroundColor = "Black";
    console.log("off");
    sta.textContent = "Light is off";
  }
}

swt.addEventListener("click",updateConsole);

function updateConsole() {
  if(swt.click === true) {
    console.log("")
  }
  else{
    console.log("swtClick")
  }
}

This is what I tried

swt.addEventListener("keydown", updateEgg);

function updateEgg() {
  if(html.keydown === true){
    console.log("easter egg found")
    alert("You found the easter egg!!!");
  }
  else{
    console.log("")
  }

Upvotes: 1

Views: 1443

Answers (2)

Darkwing
Darkwing

Reputation: 7595

Here is a fiddle:

https://jsfiddle.net/6p7590or/1/

html.addEventListener("keypress", updateEgg);

function updateEgg(e) {
  if(e.key === "u"){
    console.log("easter egg found")
    alert("You found the easter egg!!!");
  }
  else{
    console.log(e.key)
  }
  }

Upvotes: 0

mu_sa
mu_sa

Reputation: 2725

If I understood you correctly then what you are aiming for can be achieved by.

html.addEventListener("keydown", updateEgg);

function updateEgg() {
   if (event.keyCode == 85 /*checks for u press*/) { 
     console.log("easter egg found")
     alert("You found the easter egg!!!");
   }
}

The if statement checks if the key being pressed was 'u'. For keycodes you might find https://keycode.info/ useful.

Upvotes: 2

Related Questions