Javascript detecting key press event only firing once when a key is continuously held down

I have implemented the code below to redirect to a specific page when the w, s, a, d keys are pressed.

<script>
document.addEventListener('keydown', function(e){
e = e || window.event;
key = e.keyCode || e.charCode;
var keys = { 
  87: '{$up}', 
  68: '{$right}', 
  83: '{$down}', 
  65: '{$left}'
};
if (keys[key]) window.location.href = keys[key];
});
</script>

The PHP variables store the URL addresses.

My query is whether it is feasible to make the keypress register only once per click. Currently, if you hold the key down, it triggers repeatedly.

Appreciate any suggestions or advice.

Answer №1

Experiment with the 'keypress' event:

<script>
document.addEventListener('keypress', function(event){
event = event || window.event;
keyPress = event.keyCode || event.charCode;
var keyCodes = { 
  72: '{$up}', 
  74: '{$right}', 
  75: '{$down}', 
  76: '{$left}'
};
if (keyCodes[keyPress]) window.location.href = keyCodes[keyPress];
});
</script>

Answer №2

To keep track of the pressed keys, you can maintain a list and only execute your code on keydown if the key is not already in the list. When a key is released on keyup, simply remove it from the list.

var keysPressed = {};
document.addEventListener('keydown', function(e){
  e = e || window.event;
  var keyPressed = e.keyCode || e.charCode;
  if(keysPressed[keyPressed]) return;
  keysPressed[keyPressed] = true;
  // Perform desired action
});
document.addEventListener('keyup', function(e){
  e = e || window.event;
  var keyReleased = e.keyCode || e.charCode;
  delete keysPressed[keyReleased];
});

var keysPressed = {};
document.addEventListener('keydown', function(e){
  e = e || window.event;
  var key = e.keyCode || e.charCode;
  if(keysPressed[key]) return;
  keysPressed[key] = true;
  var directionKeys = { 
    87: '{$up}', 
    68: '{$right}', 
    83: '{$down}', 
    65: '{$left}'
  };
  console.log(directionKeys[key]);
});
document.addEventListener('keyup', function(e){
  e = e || window.event;
  var key = e.keyCode || e.charCode;
  delete keysPressed[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

Safari Browser does not currently offer support for MediaRecorder functionality

[Log] Webcam permission error Error: MediaRecorder is not supported I am facing an issue while trying to record audio. The Chrome browser allows audio recording without any problem, but Safari is throwing an error. global.audioStream = await navigator.m ...

Most effective method for displaying 100 images on a single page?

I have a webpage on my site that displays 100 images, but loading them one at a time makes it look unattractive. Is there a way to make it more elegant and visually appealing? ...

Breaking circular dependencies in JavaScript is a common challenge that developers face when

Having encountered a circular dependency issue between certain JS files, I am seeking steps to resolve it. Q1: Is repositioning the require function an appropriate solution? One suggested approach to resolve this issue is to move the require() statement ...

Guidelines for crafting an intricate selector by utilizing mergeStyleSets and referencing a specific class

I'm currently in the process of developing a web application using ReactJS. In my project, I have the following code: const MyComponent = (props: { array: Array<Data> }) => { const styles = mergeStyleSets({ container: { ...

Tips for presenting HTML source code with appropriate tag coloring, style, and indentation similar to that found in editors

I need to display the source code of an HTML file that is rendered in an iframe. The source code should be shown with proper tag colors and indentations similar to editors like Sublime Text. https://i.stack.imgur.com/IbHr0.png I managed to extract the sour ...

Leveraging JavaScript and Thymeleaf to manipulate a list

I am trying to access an object from a list in JavaScript, which is being passed from the controller. Currently, I am working with Thymeleaf and Spring Boot. The list is named ${collaborateurs}. The following code snippet is functional: <script th: ...

What could be causing the issue with my dependency injection in my Angular application?

Let's get started angular.module('app', [ 'ngCookies', 'ngResource', 'ngSanitize', 'ngRoute' ]) This is my simple factory. Nothing fancy here angular.module('app') .factory(&apos ...

Ways to retrieve a variable within the init() function

My current project involves using datatables along with ajax to display information dynamically. Below is the code snippet I am working with: // Setting up the module var DatatableAdvanced = function() { // Examples of Basic Datatables var _c ...

My current array is arr=[1,2,3,4]. I recently added an element to it using arr.push(5). Now I want to rearrange the array to be [5,4,3,2,1]. Any suggestions on how to achieve this

I currently have an array in the following format: var arr = [1,2,3,4] // Add another element to the array arr.push(5) // Now, arr = [1,2,3,4,5] I want to print my array as The elements in the array arr are: 5,1,2,3,4 When I use Arr.reverse(), it retu ...

Troubleshooting a Tiny Bottom Sheet Problem in react-native

On my page, I have a bottom sheet that takes up 3/4 of the space. Then, within that bottom sheet, I open another bottom sheet that only occupies 1/4 of the space (without closing the first one). ...

How to properly adjust HTTP headers within an AngularJS factory

Looking for guidance from an Angular expert. I want to know how to modify the header for POST in the code snippet below: 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'? The provided code is as follows: var tableMod ...

Tips for concealing the ID value within a URL or parameter

I just started learning Angular JS and I have a question about hiding parameters in the URL when clicking on anchor tags to send data to another controller. I don't want any ID or its value to be visible in the URL. Is it possible to hide parameters i ...

Integrating Project Tango with Ionic and/or Angular in a cutting-edge mobile application

I'm currently working on a mobile app project and I could use some advice. The majority of the app can be developed using angular.js (and possibly ionic) JavaScript technology. However, there is one aspect that requires integration with an API, specif ...

The XMLHTTP request and Chrome developer tools do not show matching information

I am currently downloading a file in chunks using XMLHttpRequest and the Range header. Everything is going smoothly, except for when I try to determine if I have downloaded the last chunk. Here's a snapshot of the initial request and response for the ...

Using Vuex: Delay dispatch of action until websocket response received

Let's look at the given scenario and premises: To populate a chat queue in real time, it is necessary to establish a connection to a websocket, send a message, and then store the data in a websocket store. This store will handle all the websocket sta ...

Having difficulty extracting image and product names from Amazon or Flipkart pages using Jsoup

I'm having trouble retrieving the main image and product name from Amazon or Flipkart using Jsoup. This is my Java/Jsoup code: // For amazon Connection connection = Jsoup.connect(url).timeout(5000).maxBodySize(1024*1024*10); Document doc = connectio ...

JSON object containing elements with dash (-) character in their names

While I am in the process of parsing a `json` object, I encountered an element labeled as `data-config`. Here's an example: var video = data.element.data-config; Every time I attempt to parse this specific element, an error pops up: ReferenceError ...

Accessing a model's field within an Ember.js each loop

Here is the code for a route that I am working on: Calendar.DateIndexRoute = Ember.Route.extend({ model: function(data) { return {arr:getCalendar(data), activeYear: data.year, activeMonthNumber: data.month, activeDay: data.da ...

Tips on including a trash can symbol to rows in a bootstrap table using React

I am working on a table that contains various fields, and I want to add a trash icon to each row so that when it is clicked, the specific row is deleted. However, I am encountering an issue where the trash icon is not showing up on the row and I am unable ...

Running concurrently, the JavaScript if and else statements execute together

I am looking to create a clickable link that changes the background color when clicked. If the same link is clicked again, I want the background to return to its original state. Here is my current script: <div style="background: transparent;" onclick=" ...