What is the best way to incorporate the keydown event into an if/else statement?

For my middle school science fair project, I am working on creating an online light bulb that features a hidden surprise, or an "easter egg," that triggers an alert when activated by a specific key press. Below is the current code I have developed:

HTML

<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8">
    <title>Online Light Bulb</title>
    <link href = "style.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="script.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")
  }
}

Attempt to trigger the Easter Egg

swt.addEventListener("keydown", updateEgg);

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

Answer №1

If I'm understanding you correctly, achieving your goal can be done by the following:

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 is checking if the pressed key is 'u'. You can find keycode information at .

Answer №2

Take a look at this interesting code snippet:

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

html.addEventListener("keypress", detectEgg);

function detectEgg(event) {
  if(event.key === "u"){
    console.log("Easter egg discovered")
    alert("Congratulations! You found the hidden Easter egg!");
  }
  else{
    console.log(event.key)
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Gathering information from a PHP form without redirecting to a new page

Can an array be passed from JavaScript to PHP on the same page before submission? In my index.php, I have a form where changing the value of an input triggers a function to send the input value to PHP. In PHP, this value is used to make an HTTP request to ...

The property fails to reflect changes in state

I am currently developing an application that requires fetching data asynchronously and preserving the state in the parent component while also passing the data reference to children components. I encountered an issue where the props do not update when the ...

What is the process for retrieving the user's information following successful social media login?

I have implemented Firebase for authentication in plain JavaScript, without using any frameworks like AngularJS or Angular2. When a user signs up successfully with Google or Facebook, I want to display their name, email, and profile picture. firebase.auth ...

How to set the element in the render method in Backbone?

Currently, I am in the process of developing a web page utilizing BackboneJS. The structure of the HTML page consists of two divs acting as columns where each item is supposed to be displayed in either the first or second column. However, I am facing an is ...

What steps should I take to activate JavaScript type checking in Vue files within Visual Studio Code?

After much exploration, I have successfully configured Visual Studio Code to perform type checking for JavaScript within JS files. This feature highlights any bad code and provides explanations for why it is considered as such here. However, this function ...

Modify the color of the field that is currently chosen

Is there a way to modify the highlight color of the active record in an extjs combobox? In the image provided below, the record Petty Cash Fund is currently selected in my dropdown, but the highlighting is not very visible. How can I adjust this for all co ...

The method of implementing an index signature within TypeScript

I'm currently tackling the challenge of using reduce in Typescript to calculate the total count of incoming messages. My struggle lies in understanding how to incorporate an index signature into my code. The error message that keeps popping up states: ...

Bundling sub-components using Rollup for NodeJS application packaging

My ES6 library consists of several sub-modules arranged like this: - package.json - lib - my_package - file1.js - file2.js - sub_module1 - file3.js - file4.js Currently, I import modules within my package using file resolution r ...

Automatic Addition of Row Numbers Enabled

I'm currently exploring coding and experimenting with creating a scorekeeper for family games. I've managed to add rows dynamically and automatically sum up the entered information in the "total" row at the bottom. However, I'm facing an iss ...

Applying Tailwind styles to dynamically inserted child nodes within a parent div

Currently, I am in the process of transitioning my website stacktips.com from using Bootstrap to Tailwind CSS. While initially, it seemed like a simple task and I was able to replace all the static HTML with tailwind classes successfully. However, now I ha ...

What is the best way to ensure a navigation link stops scrolling at the bottom of a navbar that is set to position: sticky?

I am utilizing Bootstrap 5 for my website, and I have a sticky-top attribute on my navbar. When I click on one of the links in the navigation bar, the page scrolls to that section, but some of the content goes behind the navbar. I am looking for a way to m ...

Modify the layout of a JSON data structure

Here is an example of an array: let array = [ {1: { "date": "2014-04-23 00:00:00", "volumetrie": "22458" }}, {2: { "date": "2014-05-02 00:00:00", "volumetrie": "30585" }}, {3: { "date" ...

"Dealing with an array of routes in AngularJS $

Clicking on the Home link triggers the goTo function, but it redirects to a blank page as shown: https://i.sstatic.net/qerBI.png Upon clicking on the browser's back button, it redirects to the desired page (firstPage). https://i.sstatic.net/oaANp.p ...

Steps for updating a specific item within an object in an array of MongoDB document

Consider the following data collection, for which I have some questions: { "_id" : ObjectId("4faaba123412d654fe83hg876"), "user_id" : 123456, "total" : 100, "items" : [ { ...

Using AngularJS to handle form data without ng-model

I am facing a unique situation that may seem a bit strange. I have a form that needs to edit/update information from different objects, such as services. My goal is to use ng-model to link input fields to their respective objects, but when the form is sub ...

I encountered a 429 error while trying to make a request to the Spotify API

I recently encountered an issue with my website where I am trying to retrieve and display my playlists. Everything was working fine yesterday, but this morning I started getting error 429 every time I tried to retrieve data from the api, even though I have ...

Tally each div individually and display the count within each div, instead of showing the total count across

I have come across various solutions that show the total number of certain special divs, such as: $('.someclass').length However, I am facing a different challenge. I want to sequentially count each div with a numerical sequence. For instance, ...

Is it possible to refresh the JSViews data that is underneath using an onclick event?

I have created a photo gallery using a JSViews template which includes upvote and downvote buttons. When these buttons are clicked, it triggers a database update to increase the score. However, I am facing an issue with updating the Score field in the HTML ...

Is it possible to retrieve the BrowserWindow by its unique identifier in Electron?

Imagine if the following function is called multiple times to instantiate BrowserWindow, specifically 5 times. let mainWindow; function createWindow() { "use strict"; mainWindow = new BrowserWindow({ height: height, width: width ...

Incorporate PrimeVue into Vue's custom elements

Can you guide me on integrating a PrimeVue component into a Vue3 custom element? I have created a Vue3 composition+setup custom element. I expect the button to be styled with PrimeVue and appear red due to the severity="danger" attribute. Howev ...