Is there a way to activate a function when the up and down keys are pressed?

I'm trying to implement different functions when the up or down arrow key is pressed. Here's what I have so far:

window.addEventListener('keypress', function(e) {

    console.log("Key Pressed");

    /*Assigns "key" variable to hold the keycode of the key pressed*/
    var key = e.which || e.keyCode;

    /*Checks if the pressed key is the "up" key*/
    if (key === 38){
            functionOne();
           console.log("Up key was Pressed");
        }

    /*Checks if the pressed key is the "down" key*/     
    else if (key === 40){
            functionTwo();
            console.log("Down key was Pressed");
        }
    })

The console log message "A key has been pressed" appears whenever any key is pressed other than the arrow keys, shift, alt, caps, tab, and f1 - f12. What might be causing this issue?

Thank you in advance.

Answer №1

Consider using the keyup event as an alternative.

Keep in mind that the onkeypress event may not be triggered for certain keys (such as ALT, CTRL, SHIFT, ESC, arrows) across all browsers. To accurately determine if a key has been pressed, opt for the onkeydown event instead, since it is more reliable and works universally.

window.addEventListener('keyup', function(e) {
var key = e.which || e.keyCode;
    console.log(key);
    if (key === 38){
        console.log("The Up key was Pressed", key );
    }    
    else if (key === 40){
        console.log("The Down key was Pressed", key );
    }
    e.preventDefault();
})

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

Default page featuring an AngularJS modal dialog displayed

I am attempting to display a modal popup dialog using an HTML template. However, instead of appearing as a popup dialog, the HTML code is being inserted into the default HTML page. I have included the controller used below. app.controller('sortFiles&a ...

RegEx: determining the smallest sum of digits required in a character sequence

I'm trying to figure out a way to count the number of digits in a string that resembles a password. Currently, I am using this regular expression: ^(?=.*[0-9]{3,})([a-zA-Z0-9_/+*.-]{6,})$ It works well when there are 3 consecutive digits, but not ...

Incorporating jQuery ajax requests into divs seamlessly to avoid any page disruptions

When loading numerous ajax calls on a page, the timing of each call varies, resulting in some content loading before the user reaches the top of the page. This may cause the user to miss viewing certain data unless they scroll back up to the top. Below is ...

Troubleshooting a page refresh error displaying "file not found" when using [angular js + NodeJS/ExpressJS] - solving the

Note: In my attempt to solve all questions and answers related to this topic, I have encountered an issue. I am developing a web application using AngularJS with HTML5, NodeJS/ExpressJS, and MongoDB for the database. However, when trying to remove the &apo ...

Modifying vertices in THREE.LineSegment: Adding and deleting

I am facing an issue with a THREE.LineSegments object, where I need to dynamically change the number of vertices. However, when I try to modify the geometry vertices array, the lines with removed vertices remain in place. Is there a way to remove vertices ...

What is the process for assigning the value returned from an Angular HTTP request to ng-bind?

I am trying to retrieve a value from an HTTP request in AngularJS and set it as the result in a variable that is bound to ng-bind. The goal is for the value returned from the HTTP request to be displayed when text is typed into an input field. Below is th ...

Encountering an error message about an existing Sequelize index while running my application

I crafted this migration file: 'use strict'; module.exports = { async up(queryInterface, Sequelize) { await queryInterface.createTable('note_tags', { id: { type: Sequelize.INTEGER, allowNull: false, ...

Modification of data in amCharts4 doesn't automatically update the map display

I am integrating amcharts4 into a meteor project to display a map with dynamic map markers. These map markers need to update themselves whenever the underlying data changes. I have tried to customize the demo available at this link. The only modification ...

Displaying decimal values in Angular as percentages

In my Angular application, I have a numeric textbox that displays a percentage value and allows users to update it. https://i.stack.imgur.com/eCOKe.png <label for="fees">Fees %</label> <div class="inpu ...

Tips for utilizing the AngularJS filter to group by two columns in Angular

In my array of objects, each item has three properties: 1. name 2. team 3. age http://jsfiddle.net/HpTDj/46/ I have successfully grouped the items by team, but I am unsure how to group them by both team and age in my current code. I want to display the ...

A blank screen of errors pops up when attempting to update through a form

Encountering a white error screen when attempting to add an item using a form in Python / Django. I'm currently debugging the issue but lacking information. Any guidance on where to look next would be greatly appreciated.https://i.sstatic.net/daavn.pn ...

Is there a way to reduce the size or simplify the data in similar JSON objects using Node.js and NPM packages?

Is it possible to serialize objects of the type "ANY_TYPE" using standard Node tools.js or NPM modules? There may be multiple objects with this property. Original Json - https://pastebin.com/NL7A8amD Serialized Json - https://pastebin.com/AScG7g1R Thank ...

Enhance the code for updating the content within a div element

I recently discovered that utilizing jQuery allows for updating the content within a div. My goal now is to enhance this script so the content remains consistent, even while loading or not. Take a look at my current code: function changeContent () { va ...

Searching for 10 random data records within a collection of 100 in MongoDB

Can MongoDB retrieve a specific number of random documents in one query? For example, I currently load all the documents in the collection on the JavaScript side, which is inefficient. I'm wondering if there's a better way to achieve this with a ...

Experiencing a Node.js application issue with the error message "ERR

I'm encountering some serious challenges with a Node.js app that I am developing using Express, MongoDB, and Mongoose. Everything seemed to be functioning correctly last night when I used nodemon server.js to start the server. However, I'm now fa ...

AngularJS closes when clicked outside

I've been attempting to add a close on outside click functionality to my code, similar to this example: http://plnkr.co/edit/ybYmHtFavHnN1oD8vsuw?p=preview However, I seem to be overlooking something as it's not working in my implementation. HT ...

There seems to be an issue with JSX rendering correctly in the code

My JSX code is not rendering properly on my React webpage, and instead of the expected output, I am seeing: <div class='card'>NaNSasha<img src= NaN />Boddy Cane</div>. Here is the component's code: import React, { Componen ...

Transferring a document through an HTML form to PHP using JavaScript

I've developed a JavaScript form but I intentionally omitted the submit button since it consists of just one input field. Instead, I utilized the onchange function to achieve this. Here's what my form structure looks like: <form method="post" ...

What strategies can be employed to mitigate the activation of the losing arm in a Promise.race?

My current task involves sending the same query to multiple identical endpoints (about five) across various Kubernetes clusters. The goal is to aggregate the results without any delays and report failures to the user while continuing with the process seaml ...

VueJS does not update values instantly as they change

I have implemented a JS class with the following code: class Field { public Value = null; public Items = []; public UniqueKey = null; public getItems() { let items = [...this.Items]; items = items.filter((item) => { ...