What is the best way to implement a modal that can toggle dark mode using the Konami code, with the added functionality of a close button?

Recently, I attempted to create a Modal window that would activate when the Konami code (↑↑↓↓←→←→BA) is typed. As someone new to JavaScript, I'm still learning and open to feedback. While I have the coding part figured out, I need assistance in implementing the modal aspect. Take a look at the code below for more information:

var pattern = ['ArrowUp', 'ArrowUp', 'ArrowDown', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'ArrowLeft', 'ArrowRight', 'b', 'a'];
var current = 0;

var keyHandler = function (event) {

    // If the pressed key is not in the pattern or does not match the current key, reset
    if (pattern.indexOf(event.key) < 0 || event.key !== pattern[current]) {
        current = 0;
        return;
    }

    // Update the progress of typing the pattern
    current++;

    // If the entire pattern is successfully entered, trigger alert and reset
    if (pattern.length === current) {
        current = 0;
        // This is where the Modal feature should be implemented with options for dark mode and light mode.
    }
};

// Listen for keydown events
document.addEventListener('keydown', keyHandler, false);
<h1> Enter the Konami code. (↑↑↓↓←→←→BA) to uncover a surprise.

Answer №1

Extracted from https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal

No ownership claimed, simply a duplication

var pattern = [
  "ArrowUp",
  "ArrowUp",
  "ArrowDown",
  "ArrowDown",
  "ArrowLeft",
  "ArrowRight",
  "ArrowLeft",
  "ArrowRight",
  "b",
  "a"
];
var current = 0;

var modal = document.getElementById("myModal");

// Get the button that triggers the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

var keyHandler = function (event) {
  // If the key isn't part of the pattern, or isn't the next key in the pattern, reset
  if (pattern.indexOf(event.key) < 0 || event.key !== pattern[current]) {
    current = 0;
    return;
  }

  // Update how much of the pattern is complete
  current++;

  // If fully entered, display alert and reset
  if (pattern.length === current) {
    modal.style.display = "block";
    current = 0;
    // Modal with dark mode option and light mode (if already on dark mode(optional)).
  }
  
};

span.onclick = function () {
    modal.style.display = "none";
  };

  // Close modal when clicking outside it
  window.onclick = function (event) {
    if (event.target == modal) {
      modal.style.display = "none";
    }
  };

// Listen for keydown events
document.addEventListener("keydown", keyHandler, false);
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  padding-top: 100px; /* Location of the box */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}

/* The Close Button */
.close {
  color: #aaaaaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}
<h1> Enter the Konami code. (↑↑↓↓←→←→BA) for a surprise.</h1>

<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Some text in the Modal..</p>
  </div>

</div>

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

The unit tests are passing successfully

Trying to create unit test cases for a web API call. This one showcases success: Success Unit Test (jsfiddle) getProduct("jsonp","https://maps.googleapis.com/maps/api/e Here is an example of an error, but the test result still shows "pass": Error ...

Creating a real-time text field update feature for a form using Google Script

One of my clients is dealing with a large number of contacts and to streamline the process, I created a form with a scrolling list for contact selection. However, the list has become too long to navigate easily. Is there a solution that would allow the c ...

Error message: "AngularJS encountered a $injector:modulerr error in Internet Explorer 11."

I've successfully created an AngularJS App that functions properly on most browsers like Firefox, Opera, Safari, Edge, and Chrome. However, there seems to be a compatibility issue with IE 11. When attempting to open the app in IE 11, the following er ...

Playing sound using jQuery when the body of the page is replaced

I am facing an issue with my website where I have implemented a jQuery full body refresh every 30 seconds. However, I want to add a short sound to play every time the page refreshes. Despite trying various methods, the sound works on my computer browsers ( ...

Issues with Jquery .get() function in Internet Explorer

Encountering an issue with none other than IE8. The below code, simplified for clarity, is not functioning as expected: alert('before get'); $.get(getActivityURL('ActionName',{ ts: new Date().getTime(), ...other params...}), {cac ...

Harness the power of AngularJS by crafting your unique

Hey there! I'm having a bit of trouble figuring out why this isn't showing up. Both View1.html and View2.html are in the partials folder, so that's not the issue. Sometimes the screen is completely blank, other times I only see a Name: label ...

When trying to access a property in Typescript that may not exist on the object

Imagine having some data in JS like this example const obj = { // 'c' property should never be present a: 1, b: 2, } const keys = ['a', 'b', 'c'] // always contains 'a', 'b', or 'c' ...

There is an issue with the hook call while trying to establish a context with a reducer

I am facing an issue while setting up the AppProvider component that utilizes a context and reducer to manage global data for my application. The problem seems to be arising from the useReducer hook used within the AppProvider. I have checked the error mes ...

Objects may unexpectedly be sorted when using JavaScript or Node.js

When I execute the following code using node app.js 'use strict'; var data = {"456":"First","789":"Second","123":"Third"}; console.log(data); I am receiving the following output: { '123': 'Third', '456': 'F ...

How can I dynamically change a key in an object and replace it with a custom name while also updating its value?

Transform this =>>>>> {1: "Baroque", 2: "Glitch Pop ", 3: "Nu Jazz", 4: "Drumfunk", 5: "Bitpop", 6: "Latin Pop", 7: "Carnatic"} into this ==>>>> [{id: 1 name ...

NextJS displays outcomes as per query parameters obtained from an external API

I have set up my NextJS app to connect to a rest API. The API returns results based on different filters in the query string, such as: /jobs /jobs?filter=completed /jobs?filter=upcoming /jobs?filter=cancelled On my NextJS page, I have a few buttons that I ...

How can I update information based on the chosen option in a select dropdown using Vue?

I have a chart displayed in my user interface that needs to be updated based on the selected time period. By default, the chart displays data from the past year, but when the user selects "Month," it should show data from the past month. <div cla ...

Is it possible to refresh resources in Node.js without the need to restart the server?

Is there a middleware or library that allows access to files added after the server starts without requiring a restart? I currently use koa-static-folder, but it seems unable to handle this functionality. ...

Having trouble locating the name WebGLObject in my TypeScript code

Every time I try to run ng serve command An error pops up on my screen saying: "WebGLObject cannot be found." ...

Using AngularJS to bind objects with a checkbox

I am dealing with a nested list of objects that can go up to three levels deep. Each object contains another nested object, and this nesting can continue to multiple levels. I am interested in binding these objects directly to checkboxes so that when I che ...

Tips for passing a variable from one function to another file in Node.js

Struggling to transfer a value from a function in test1.js to a variable in test2.js. Both files, test.js and test2.js, are involved but the communication seems to be failing. ...

execute php function when form is submitted

Hello, I am attempting to create a code using this PHP function: <?php function generateRandomString($length = 6) { return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/str ...

What are the steps for incorporating React into an existing website?

Currently, I have a website built with Express and I am looking to incorporate React into specific pages. What is the most effective method to integrate it while utilizing all the resources available through create-react-app? I understand that I can manua ...

Guide to sending client-to-client notifications in Angular/Ionic with Firebase Cloud Messaging

I am looking to implement client-client push notifications (not server-to-client). My goal is to send a notification when one user messages another. Is this feasible? How can I achieve this using the structure in the Firebase real-time database? Here is a ...

Include the window.innerWidth value in the initial GET request

When dealing with a server-side rendered app that has responsive styling based on window.innerWidth, the challenge lies in how to pass the client's screen size in the initial GET request for index.html. This is crucial so that the server can prepare a ...