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

REGEX: All characters that appear between two specified words

Is it possible to use Regex to select all characters within the designated words "Word1 :" and "Word2 :"? I am looking to extract any character located between these two specific phrases. Word1 : Lorem ipsum dolor sit amet consectetur adipiscing elit ...

Material UI AppBar displaying custom colors instead of theme colors

Currently, I am utilizing Material UI version 4.7.0. In my project, I have established a customized theme (shown below) by utilizing createMuiTheme() method with personalized primary and secondary colors set. Within my AppBar component (also displayed be ...

Activate or deactivate a text box within a table based on the checkbox's status

I am seeking assistance with jQuery to enable or disable a textbox within a table when a checkbox is checked. Below is the code snippet from my edit.cshtml file. <table id="scDetails" class="dataTable"> <thead> & ...

Choose an option with JavaScript once the request is successful

Choose the day, month, and year using JSON data success: function(jsondata){ var data=JSON.parse(jsondata); var list_html="<div id='editrelation'><label id='dateLabel' style='display:none&apo ...

The process of implementing sticky headers that stay in place while scrolling in a React application

I have a challenge with organizing tables based on date, using headers like (today, yesterday, last week, ...) and I want to make them sticky depending on the current table in the viewport. I attempted to implement this functionality using the react-sticky ...

When I try to run Parcel, my ReactJS website just won't deploy in a serverless environment

For a while now, I've been working on a website using serverless. Everything was going smoothly until this morning when I encountered an issue with pushing updates from my site to the serverless platform. When trying to push, I received the following ...

What is the reason that the for loop updates all indexes in Node.js?

Currently, I am working on a space battle program that involves nested arrays. In order to simulate fleet fighting, I have written the following code: //Roll a dice function const randomNumber = (number) => { return Math.floor(Math.random() * numbe ...

Sophisticated web applications with Ajax functionalities and intricate layouts powered by MVC frameworks

I am looking to integrate an ajax-driven RIA frontend, utilizing JQuery layout plugin (http://layout.jquery-dev.net/demos/complex.html) or ExtJs (http://www.extjs.com/deploy/dev/examples/layout/complex.html), with... a PHP MVC backend, potentially using ...

Fixing My Code with JQuery Tabs and Hyperlinking

I have come across a problem while using multiple pages with jQuery tabs. Let's consider Page1.html with #tab1 and #tab2, and Page2.html with #tab3 and #tab4. Here are the issues I am facing: 1) Within the tab content of Page1.html#tab2, there is a h ...

Converting Markdown to HTML using AngularJS

I'm utilizing the Contentful API to retrieve content. It comes in the form of a JSON object to my Node server, which then forwards it to my Angular frontend. This JSON object contains raw markdown text that has not been processed yet. For instance, t ...

Utilizing Office.js: Incorporating Angular CLI to Call a Function in a Generated Function-File

After using angular-cli to create a new project, I integrated ng-office-ui-fabric and its dependencies. I included in index.html, added polyfills to angular.json, and everything seemed to be working smoothly. When testing the add-in in Word, the taskpane ...

Vue template is not being rendered when served through Django

I am currently working on a Django application where Vue is used as the frontend to render templates. In my Django view code, I have the following components: # thing/views.py def index(request): template = loader.get_template('thing/index.html&a ...

What is the best way to generate a "JSON diff" that can be displayed in the JavaScript console?

When working on my Angular project, I frequently encounter the need to compare JSONs in my Karma/Jasmine tests. It would be incredibly useful to have a console output showing what has been added and removed when comparing two structures. For example, ident ...

My API is feeding data to the Material UI CardMedia image

Has anyone encountered a similar error while using the CardMedia API provided by Material-UI? I am currently utilizing the Card & CardMedia components from material-ui to display data fetched from an api. However, I am facing difficulty in displaying ...

Dealing with an unspecified parameter can be tricky - here's how you

Currently, I am in the process of developing an angular application. In this project, there is a specific scenario that needs to be handled where a parameter is undefined. Here's a snippet of my code: myImage() { console.log('test') ...

Refresh TR when clicked

I have a HTML table that lists items from SQL, using <tr> and <td>. The table is housed within a div that is refreshed every 30 seconds with jQuery AJAX (hence the unique id on the div). Here is the HTML code: function auto_load() { $.aj ...

After the request.send() function is called, the request is not properly submitted and the page automatically redirects

I'm currently working on a basic ajax comment form that includes a textarea and a yes/no radio button. If the user selects 'yes', their comments are posted and then they are redirected to a new page. If the user selects 'no', th ...

Tips for updating VUE's main.js file to incorporate the routers/index.js configuration

What is the reason for the difference in syntax between the VUE UI main.js code generated by CLI/3 and the older version, and how does it function? What are the various components of the new syntax and how do they work? sync(store, router) // for vuex-rou ...

Guide on how to use JavaScript to make an HTML5 input field mandatory

I am facing an issue with setting input fields as required based on radio button selection in a form. Initially, all fields should have required=false, but I'm unable to achieve this. No matter what value I assign to the required attribute, it always ...

partial download between servers

I have been attempting to transfer/copy a large file from a remote server to my server in segmented parts or chunks. My initial approach involved utilizing a script I found here: . After making some modifications, I integrated a form into the script and e ...