Increase and decrease buttons using the 'keydown' event (ArrowUp and ArrowDown)

I'm seeking assistance with a school project. I currently have two buttons, one for incrementing and one for decrementing. There are four functions in total, two for clicking and two for using arrow keys. The clicking functionality works fine, but when it comes to the arrow up and arrow down keys, I notice that I need to first click and select the button with the mouse before the arrow keys start working. Is there a way I can modify the lower arrow key functions so that they work without the initial click?

let element = document.querySelector('#value')
let buttonIncrease = document.querySelector('#increase')
element.textContent = '1'
let buttonDecrease = document.querySelector('#decrease')
buttonDecrease.disabled = true;

//Increment number by 1 on click
buttonIncrease.addEventListener('click', () => {
  element.textContent = Number(element.textContent) + 1
  if (element.textContent > 1) {
    buttonDecrease.disabled = false;
  }
})

//Decrement number by 1 on click
buttonDecrease.addEventListener('click', () => {
  element.textContent = Number(element.textContent) - 1
  if (element.textContent < 2) {
    buttonDecrease.disabled = true;
  }
})

//Increment number by 1 on keydown
buttonIncrease.addEventListener('keydown', (up) => {
  if (up.key === 'ArrowUp' ) {
    element.textContent = Number(element.textContent) + 1
  }
  if (element.textContent > 1) {
    buttonDecrease.disabled = false;
  }
})

//Decrement number by 1 on keydown
buttonDecrease.addEventListener('keydown', (down) => {
  document.getElementById('decrease')
  if (down.key === 'ArrowDown') {
    element.textContent = Number(element.textContent) - 1
  }
  if (element.textContent < 2) {
    buttonDecrease.disabled = true;
  }
})

Answer №1

Clicking on the increment and decrement buttons automatically activates the function without needing to specify a specific muse.

However, in order to use arrowUp and ArrowDown keys, it is necessary to initially click and select the button with the mouse for the function to take effect.

You can detect when the arrowUp and arrowDown keys are clicked by adding an event listener directly to the keyboard:

addEventListener("keydown", function (e) { // Do something }

Answer №2

To achieve the desired outcome, you can assign the keydown event handler to the window element. This way, regardless of which element in the document object model (DOM) is currently focused, as long as the event can propagate up to the window element, the value will be updated.

It's worth noting that you have the option to consolidate multiple keydown event handlers into a single one. Additionally, you can enhance the efficiency and maintainability of your code by encapsulating repetitive logic in functions:

let buttonIncrease = document.querySelector('#increase');
let buttonDecrease = document.querySelector('#decrease');
let element = document.querySelector('#value');

buttonDecrease.disabled = true;
element.textContent = '1';

const setButtonState = () => buttonDecrease.disabled = parseInt(element.textContent, 10) <= 1;
const updateValue = increment => {
  value.textContent = Math.max(1, Number(element.textContent) + increment);
  setButtonState();
}

buttonIncrease.addEventListener('click', () => updateValue(1))
buttonDecrease.addEventListener('click', () => updateValue(-1))

window.document.addEventListener('keydown', e => {
  e.preventDefault();
  let value = Number(element.textContent);
  let increment = e.key === 'ArrowUp' ? 1 : e.key === 'ArrowDown' ? -1 : 0;
  updateValue(increment);
})
#value {
  padding: 3px;
}
<button id="decrease">-</button>
<span id="value">1</span>
<button id="increase">+</button>

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

Most efficient method for dynamically changing HTML content with JavaScript

Can anyone provide guidance on how to switch HTML content using JavaScript? For example: if($sid == 0) {insert one HTML code} else {insert another HTML code} Which method is preferable - LESS, jQuery, CSS3, etc? ...

Using React to incorporate the necessary jquery for a separate library

I am looking to incorporate Trumbowyg library into my React project, however, I have encountered an error stating that jQuery is not defined. I found information suggesting that jQuery needs to be made available as a global variable in the window object. ...

Click on a button to completely remove all JavaScript from your website using jQuery

I'm currently experiencing some difficulties with my website Concept Studio. On a specific page, I have a typing animation within a form and I'd like to include a button that allows users to skip the animation. However, I'm unsure of how to ...

Retrieving data from router in Angular

I have been working on a web application using Angular, and I have implemented a fixed header in the index.html file. The header appears on every page, with content injected through a ui-view. However, I now want to display this header only after the user ...

Tips for wrapping a div around its floated children

I'm currently developing a website for an online shopping cart and working on making the search results responsive. I am aiming to display as many items as possible across the screen (usually 3) when viewed on any device with a resolution lower than t ...

Tips for formatting a phone number using regular expressions in [Vue 2]

I am currently working on creating regex code that will meet the following requirements: Only allow the first character (0th index) in a string to be either a '+' symbol or a number (0-9). No non-numerical values (0-9) should be allowed anywhere ...

Incorporate a delay when using jQuery's mouseenter function

I'm trying to implement a tooltip that appears 5 seconds after the mouse enters. Here's the code I've been working with: $('thead').mouseenter( function() { var tooltip = $('<div id="tooltip" class="tooltip-container ...

Display a substitute image if there is no internet connection available to load the Google Map Canvas

I have a WebApp that runs locally, but it's possible that users may not always have access to 3G/WiFi when using the app. This means that the Google Map will not load without an internet connection since it requires the web API. In order to provide a ...

What is the method for retrieving an image source using JavaScript?

I'm trying to retrieve the image source from my utils file and bind it to an img tag in my About.vue JS file, but I'm facing issues with the implementation. The first file is About.vue, and the second one is my utils file. <template> < ...

Encountering difficulties while attempting to deploy NodeJS application on Heroku

When attempting to deploy my nodejs app, I encountered the following error: 2019-11-25T18:16:16.927748+00:00 app[web.1]: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9a8a7a6a7b0a4a6bcbae4afa6bbbca4e4ada0baaabcbabaa0a6a ...

Leveraging jQuery's $.getJSON method to fetch localization data from aprs.fi

Utilizing JSON to retrieve localization coordinates from is my current goal. I came across an example on http://api.jquery.com/jQuery.getJSON: <script> $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", { tags: ...

Can a specific element be chosen based on its background color?

Is it possible to change the background color of a child element within a div that has a specific background color using CSS? See my explanation below. For example: .container[background-color=some color] .content { background-color: some other color ...

Combining Option Value and Name Selection Using React Hooks

Currently, I am facing a situation where I need to retrieve two different values (item.id and item.name) to set the State when selecting an item from my dropdown menu. Right now, I am only able to do this for one value (item.id). Is it possible to achieve ...

Setting a value in the selectpicker of rsuitejs involves assigning a specific value to the

const _DATA = [{ code: 'code1', name: 'Jagger' },{ code: 'code2', name: 'Tigger' },{ code: 'code3', name: 'Lion' }] <SelectPicker data={_DATA.map(x => {return {label: x.n ...

What is the best way to make IE 10 display a pointer instead of an I-bar for a select list?

Is there a way to make IE 10 display a pointer instead of an I-bar when selecting from a list? Despite trying various methods found in similar questions, I have been unable to resolve this issue. The cursor: pointer property works as expected on other br ...

jQuery appears to be unresponsive or inactive

I'm trying to implement a jQuery script that will slide in a header after scrolling on the page, but for some reason, it's not working. When I reach the 3rd line, my code editor displays a !read only alert, suggesting there may be a syntax issue? ...

Here is a step-by-step guide on how to use JavaScript to eliminate the page title, URL, date and

When printing a page using window.print, is there a way to exclude the page title, URL, page number, and date/time from appearing? ...

next-redux-wrapper is being invoked repeatedly and experiencing multiple calls to HYDRATE

I'm embarking on a new Next.js project, transitioning from a standard React app to a Next.js application. Our plan is to utilize Redux Toolkit for global state management and incorporate server-side rendering. During this process, we discovered the ne ...

Exploring protractor and webdriver basics in the context of a non-angular application

Currently, I am in the process of writing end-to-end tests for a non-angular application using Protractor. While there is a wealth of information available on how to achieve this, it appears that there are multiple approaches to consider. This has led me ...

Issue with button events not being triggered while working with dynamically created classes

I am facing an issue with three plus (+) buttons that are next to three separate tables built using DataTables. The problem arises because all the plus buttons were created in one location with DataTables, resulting in them being assigned the same classes ...