Javascript - Incrementing value upon key press, but limited to occurring only once

I am currently working on a script where I need to increment a variable by 5 each time the up key is pressed. The issue I am facing is that the variable keeps increasing continuously from a single keypress, whereas I want it to increase in steps of 5 (e.g., 5, 10, 15, 20...).

Below is the code I have written so far. Any help in identifying my mistake would be greatly appreciated.

var projectileHeight = 5;

function setHeight()
{
    projectileHeight += 5;
};

if (keyCode == 38)
{
    setHeight();
    console.log(projectileHeight);
};

The code related to the keycode for the up key is placed within a rendering function used with requestAnimationFrame(). Moving this outside the function did not resolve the issue.

Javascript is being used alongside THREE.js & Physi.js.

Additional code:

var render = function() {
            requestAnimationFrame(render);
            scene.simulate();

            let keyFlag = false;

            document.addEventListener("keydown", (e) => {
                if(e.code == 'ArrowUp'){
                    if (!keyFlag) {
                        keyFlag = true;
                        projectileHeight += 5;
                        console.log(projectileHeight);
                    }
                }                
            });

             document.addEventListener("keydown", (e) => {
                if(e.code == 'ArrowDown'){
                    if (!keyFlag) {
                        keyFlag = true;
                        projectileHeight -= 5;
                        console.log(projectileHeight);
                    }
                }                
            });

               document.addEventListener("keyup", (e) => {
                if(e.code == 'ArrowUp' || e.code == 'ArrowDown'){
                    if (keyFlag){
                        console.log("stopped");
                        keyFlag = false;
                    }
                }
            });

            renderer.autoClear = false;
            renderer.clear();
            renderer.render(backgroundScene, backgroundCamera);
            renderer.render(scene, camera);
        };

This function includes keypress detection within the render function and initiates animation frames and game physics.

The function is called immediately after declaration.

Thank you for your assistance.

Answer №1

In order to keep track of whether a key is being held down or not, you should set a flag to indicate this state. A simple way to achieve this is by utilizing the keydown event along with the keyup event. The code below demonstrates how the key can be continuously pressed while triggering an action only once based on the flag.

i.addEventListener("keydown", (e) => {
  if (!keyflag) console.log(e.key);
  keyflag = true;
});

i.addEventListener("keyup", (e) => {
  if (keyflag) console.log("released!");
  keyflag = false;
});

let i = document.querySelector("input"),
  keyflag = false;

i.addEventListener("keydown", (e) => {
  if (!keyflag) console.log(e.key);
  else e.preventDefault();
  keyflag = true;
});

i.addEventListener("keyup", (e) => {
  if (keyflag) console.log("released!");
  else e.preventDefault();
  keyflag = false;
});
<input>

Note: In the provided code snippet, e.preventDefault() is used to prevent letters from appearing in the input box when keys are pressed. This was done solely for clarity and ease of understanding.

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

Executing several asynchronous functions in Angular 2

I am currently developing a mobile app and focusing on authentication. In order to display data to the user on my home page, I need to connect to various endpoints on an API that I have created. Although all endpoints return the correct data when tested i ...

Update picture using Vanilla Javascript for mobile display

I am looking to change my logo color to white when viewed on mobile devices. Currently, I have the following code for changing the logo on scroll using vanilla JavaScript. The code toggles between a dark and light logo based on the scroll position. Howev ...

simulated xhr server along with the locales in polymer appLocalizeBehavior

Currently, I am in the process of developing a web frontend utilizing Polymer. Within my web component, I incorporate various other components such as paper-input or custom web components. To facilitate testing for demonstration purposes, I have integrated ...

Implementing a JQuery function to generate a popup whenever a user clicks on a table row (tr) in an

I am working on a JSP page that contains a table, and I want to implement a pop-up window functionality when clicking on a specific row in the table. I have attempted to use JavaScript to connect with the row but so far, I have not been successful in creat ...

I am facing an issue where the text I included is not appearing on the website that

While developing a React version of my online portfolio, I encountered an issue. Once deployed on GitHub pages, the text on my landing and contact pages disappeared. Despite removing the background image thinking it might be hiding the text, the issue pers ...

How can I showcase array elements using checkboxes in an Ionic framework?

Having a simple issue where I am fetching data from firebase into an array list and need to display it with checkboxes. Can you assist me in this? The 'tasks' array fetched from firebase is available, just looking to show it within checkboxes. Th ...

Having trouble sending data from AJAX to PHP

My goal is to implement a "load more" feature in my web app that automatically calls a PHP file to load additional products as soon as the page is fully loaded. In order to achieve this, I am using AJAX to call the PHP file: $(document).ready(function() { ...

Navigating asynchronous URL parsing in NodeJS

I am still fairly new to the world of Node.js and Javascript, so I appreciate your patience with my confusion around the callback mechanism Bacchanalia. The Issue at Hand I'm currently working on a basic Node.js application that is responsible for h ...

The most secure method for retrieving User Id in AngularFire2

I'm currently facing a dilemma in determining the most secure method to obtain an authenticated user's uid using AngularFire2. There seem to be two viable approaches available, but I am uncertain about which one offers the best security measures ...

Automatically choose radio buttons within an li element in a loop

Hey there, I'm new to SO and this is my first question. As a bit of a newbie, I found this jquery code snippet on another SO answer that I want to use. The function I'm aiming for is the same, but the markup structure in my HTML is different bec ...

I encountered an issue while attempting to utilize a JavaScript script - I received an error message stating "Uncaught ReferenceError: jQuery is not defined."

Currently, I am utilizing a template with multiple pages and I need to use one of them. I followed all the necessary steps correctly, but I encountered an error in the console that says Uncaught ReferenceError: jQuery is not defined. Below is my HTML scrip ...

Tips for creating a useState variable within the render() function in reactjs

I'm completely new to reactjs, and I've been trying to define useState variables within the render() method of a reactjs component. However, I keep running into an error: "Invalid hook call." class ProductDefinition extends Component { construc ...

NodeJS controller function to generate and send a response

I'm facing an issue with my controller method where I am unable to send a response to the user, even though the value is displaying in the console. Below is my code snippet: const hubHome = (req,res) => { const hubId = req.params.hubId; fetch ...

Learn how to call class methods using jQuery events by utilizing the on() method

I'm attempting to create a reusable "component" using both HTML5 and accompanying JavaScript code that can be utilized multiple times. First, let's examine the HTML5 component code: <div class="listEditor" id="myStringList"> <div id="li ...

How to insert a row above the header in an Excel sheet using JavaScript within

i am using excel js to export json data to excel. The json data is successfully exported to the sheet, but now I need to add a row that provides details of the sheet above the header text. for more details please refer image the code is shown below: i ...

Dynamic sizing of HTML elements

I'm currently developing a timeline feature using slick slider and I'm exploring ways to dynamically adjust the vertical line height for each event based on the text content. You can view the current timeline implementation at the following link ...

Using Vite for creating a production build: A step-by-step guide

Just getting started with Vite and ready to take it into production. I'm wondering how I can create scripts (specifically for docker) to successfully run it in a production environment. The documentation strongly advises against using the preview mod ...

The most efficient method for documenting $.trigger in JavaScript/jQuery is through the use of JSD

When it comes to documenting in jsDuck, what is the optimal method for capturing the following event trigger: $(document).trigger('myCustomEvent'); ...

Tips for converting a parent class Sprite into a subclass MySprite in Cocos2d-JS

There is a custom class called MySprite that extends Sprite and includes additional methods. var MySprite = cc.Sprite.extend({ ctor:function(){ this._super(); }, doSomethingStrange:function(){ //meow meow } } ); In the game s ...

Creating personalized functions in Object.prototype using TypeScript

My current situation involves the following code snippet: Object.prototype.custom = function() { return this } Everything runs smoothly in JavaScript, however when I transfer it to TypeScript, an error surfaces: Property 'custom' does not ex ...