What is the process for updating the boolean value of a property within an object stored in an array?

I am completely new to the world of coding and am currently diving into learning javascript. Please excuse any misunderstandings I may have as I navigate this new territory. While I've been successful in grasping the basics through self-teaching, I have encountered a roadblock when attempting to detect multiple keypresses simultaneously. After researching various methods, it seems that the general approach involves tracking key events on 'keydown' and 'keyup'. However, I am struggling with setting keyBoard['w'].pressed = true.

const keyBoard = {
    w: {pressed: false}
}

document.addEventListener('keyDown', (e) => {
    keyBoard[e.key].pressed = true
});

if(keyBoard['w'].pressed){
    alert("success!")
}

The code above represents a simple test case I created to help me better understand the concept. Despite experimenting extensively, it is evident that the issue lies in accurately setting 'w.pressed' to true. I recognize the necessity of incorporating a 'keyup' listener to reset it to false eventually, but for now, my main focus is on resolving the current challenge. Your assistance is greatly appreciated!

Answer №1

To incorporate your IF statement into your listener function, make sure to use 'keydown' instead of 'keyDown'. Additionally, I included a line that records each key press in your object.

const keyboard = {
  w: {
    pressed: false
  }
}

document.addEventListener('keydown', (e) => {
  keyboard[e.key] = keyboard[e.key] || {}
  keyboard[e.key].pressed = true;
  console.log(keyboard)
  if (keyboard['w'].pressed) {
    console.log("Success!")
  }

});

Answer №2

Let's start by addressing the issue with your event handling. The correct event name should be keydown, not keyDown. You can find more information about it on MDN: keydown event documentation

Looking at your code, the problem lies in how you are trying to add a value to a non-existing key in your object. This will result in an error being thrown:

Cannot set properties of null (setting 'pressed')

To observe this error, open the browser console with F12.

The solution involves checking if the key exists in the object before setting its property. Here's how you can update your event listener to handle this scenario:

document.addEventListener('keydown', (e) => {
    keyBoard[e.key] = keyBoard[e.key] || {};
    keyBoard[e.key].pressed = true;
});

By making this modification, you ensure that the key is properly initialized before setting its attribute.

Now, let's focus on achieving the desired functionality of triggering an alert when the w key is pressed. Since the script runs during the page load, the initial if statement won't execute as intended. To make the alert work correctly, incorporate it within the event listener:

document.addEventListener('keydown', (e) => {
    if (e.key === 'w') {
        alert("success");
    }
});

Answer №3

Examining your code in three sequential blocks:

  1. Defining a constant with an object
  2. Attaching an event to the document
  3. Checking the status of the object

Everything appears to be in order, but when attaching an event, the code execution does not halt until the event occurs. Therefore, the main thread continues running and the keyBoard object remains unchanged in the third step.

To rectify this, you should monitor the variable within a loop, for example:

setInterval(() => {
  if (keyBoard['w'].pressed){
    alert("success!")
  }
}, 10);

although it may not be necessary in this scenario.

The correct approach is to allow your code to execute a method every time a key is pressed or released:

const keyBoard = {
    w: {pressed: false}
}

document.addEventListener('keydown', e => {
    keyBoard[e.key] ||= {};
    keyBoard[e.key].pressed = true
    doImportantStuff();
});

document.addEventListener('keyup', e => {
    keyBoard[e.key] ||= {};
    keyBoard[e.key].pressed = false; // or better `delete keyBoard[e.key];`
    doImportantStuff();
});

function doImportantStuff() {
    console.log(Object.entries(keyBoard));
}

If you only need to track the pressed state for each key, your code could be simplified slightly by omitting the pressed property:

const keyBoard = {}

document.addEventListener('keydown', e => {
    keyBoard[e.key] = true
    doImportantStuff();
});

document.addEventListener('keyup', e => {
    keyBoard[e.key] = false; // or better `delete keyBoard[e.key];
    doImportantStuff();
});

function doImportantStuff() {
    console.log(Object.keys(keyBoard).filter(key => keyBoard[key]));
    // console.log(Object.keys(keyBoard)); if you delete keys from keyBoard when they are released
}

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

Tips for Optimizing Navigation with Jquery Integration

I have implemented a dynamic navigation system using jQuery, where I load the navigation from a separate nav.html file to avoid updating it on every page manually. However, I am facing an issue with targeting elements in the loaded navigation to make them ...

Having trouble with TypeScript configuration of typeRoots and types functionality not functioning correctly

My Current Directory Structure Let me show you the layout of my files: root ├──typings/ # currently empty ├──package.json ├──package-lock.json ├──tsconfig.json └──main.ts This is what my tsconfig.json looks like: { ...

Leveraging Vue slots to display a component inside another component

I am currently working on creating a base modal component that can be re-used, utilizing slots to insert the modal content. The issue I am facing is that when the modal is triggered by clicking a button, it displays without any content present. How can I e ...

Eliminating the selected option from the dropdown menu after it has been added with Angular

HTML Code <!doctype html> <html ng-app="plunker"> <head> <meta charset="utf-8> <title>AngularJS Plunker</title> <link rel="stylesheet" href="style.css"> <script> document.write("<base href=&b ...

VB .Net - Issue with array index being out of range

Hello, I am a beginner in VB.Net and have been tasked with writing user methods for Power, Square, Cube using an Interface. However, when I compile the code, I encounter the error: Exception Caught: Array index is out of range I am unsure where I have ma ...

The design of iOS7 Safari becomes distorted when the orientation changes and an input field is in focus

It appears that there is a major issue in iOS7 on iPhone and iPad devices, and possibly on other versions as well. When you focus on an input field, causing the keyboard to open, the layout experiences a severe and irreversible disruption upon changing or ...

Guide to looping through a map arraylist in JavaScript

Here is a sample map arraylist. How can I access this arraylist using JavaScript from within pure HTML? And how can I iterate over this list? <%@page import="org.json.simple.JSONObject"%> <%@page import="org.json.simple.JSONArray"%> <% JSON ...

Sending information from the parent component to the child Bootstrap Modal in Angular 6

As a newcomer to Angular 6, I am facing challenges with passing data between components. I am trying to launch a child component bootstrap modal from the parent modal and need to pass a string parameter to the child modal component. Additionally, I want t ...

What is the process for a browser to load JavaScript resources?

I decided to do some research on how browsers load resources like CSS, JS, Images, HTML, etc. After creating a prototype code based on my findings, I became a bit confused during testing. Below is the Plnkr code where I included a <script> tag to int ...

Exporting a module that will return undefined instead of a value

I'm puzzled as to why the exported function findChilds is returning undefined This is how the function appears: const Folder = module.exports = mongoose.model('folder', FolderSchema); module.exports = { findChilds: (folderId) => ...

I'm currently attempting to incorporate the Material-UI InfoIcon into my code, but I'm unsure of how to properly integrate it within a TextField component

I am attempting to integrate the Material-UI InfoIcon into my TextField code, but I'm unsure of how to go about it. Here is the snippet of Material-UI code: <InfoIcon fontSize="small" /> This is where I would like to place it: <Grid item ...

A guide on clearing the selected value in a dropdown menu with Angular.js

Can someone assist me with setting the drop-down value to blank after completing an action in Angular.js? Below is my code explanation: <div style="height:270px; overflow-x:hidden; overflow-y:scroll;" ng-show="viewOrderTable"> <div class="table-r ...

Guide on utilizing two separate collections to store different types of data for an application's users

I am looking to create a database collection similar to {username : "jack", password : "pass"} for storing doctors' login information. I believe I can achieve this during signup by implementing the following code: var Doctor = mongoose.model("doctor" ...

Tips for performing an Ajax GET request in order to retrieve data from a Rails server and then transferring it to JavaScript (specifically for use with

I am working on displaying locations from a model with latitude and longitude columns on a Google Map using Ajax and JavaScript. My current approach involves the following code: map.js: function initialize() { var map; var latlng = new google ...

Displaying error messages on a form that uses ng-repeat in Angular

I am trying to dynamically generate input fields using ng repeat in Angular, but I am encountering an issue where error messages only appear on the last element. How can I make these error messages apply to each individual element? <form name="setPla ...

Having trouble getting the `load` event to fire on Safari in the window.addEventListener function?

Is there a way to automatically redirect a page after it has loaded and retrieve parameters from the URL without requiring user input? I have tried using a button click, but I would like to achieve the redirection automatically. Currently, I am using windo ...

Simple method for converting pixel values to em units

I'm searching for a simple method to incorporate a line of code into one of my plugins in order to convert specific pixel values into em values. My project's layout requires the use of ems, and I'd prefer not to rely on external plugins for ...

The dynamic duo of MongoDB and Prisma: forging a groundbreaking one-to-many relationship

Is it possible to establish a one-way m-to-n relationship without requiring both collections to have each other's ids? I am attempting the following: model Country { id String @id @default(auto()) @map("_id") @db.ObjectId ...

Determine the time variance in hours and minutes by utilizing the keyup event in either javascript or jquery

There are 6 input fields, with 5 input boxes designated for time and the result expected to display in the 6th input box. See the HTML below: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input ty ...

jQuery's jqXHR deferreds do not link up with $.when(...) for chaining purposes

When dealing with multiple promises that need to be resolved, the go-to method is using jQuery's $.when() function to wait for all of them: let test = $.Deferred(); $.getJSON('test.json') .done((content) => { test.resolve(con ...