A secondary operation is triggered in the simulated keyboard when the enter or space key is pressed, even when it is not warranted

In my HTML, I have created a simulated keyboard with buttons that correspond to characters. When you click on these buttons, the character is added to a text element on the screen. Additionally, you can use your physical keyboard to input characters in the same way.

However, I've encountered an issue where pressing the spacebar or enter key on the physical keyboard after clicking an onscreen button causes the character from the button to be repeated. This problem only occurs with the space and enter keys, and only when using the physical keyboard in combination with clicking an on-screen button.

To better illustrate the bug, here is a code snippet. Click on the interactive area to focus it and then start typing. Everything should work fine until you click the 'a' button followed by pressing the spacebar - at which point 'a' starts repeating unnecessarily.

window.addEventListener('keypress',function(e) {
  // console.log(e.key);
  keyClick(e.key);
}
);

function keyPress(key) {
  if (key == "Space") {
    document.getElementById('text').textContent = document.getElementById('text').textContent + " ";
  }
}
function keyClick(key) {
  // console.log("poop");
   if (key == "Space") {
    document.getElementById('text').textContent = document.getElementById('text').textContent + " ";
  } else {
    document.getElementById('text').textContent = document.getElementById('text').textContent + key;
  }
}
<body>
  <div id="text"></div>
  <button id="a" onClick="keyClick(this.id)">a</button>
</body>

Initially, I thought the issue might be due to different functions handling the physical and simulated keyboards. However, even after combining them, the problem persists. By adding a parameter to the function, I noticed that the extra character is being triggered by the onclick event of the HTML button when I press the spacebar key. It seems like there's something obvious I'm overlooking, or perhaps this is just a strange bug.

Answer №1

The issue occurs when the button remains in focus and the space bar is pressed, causing both a click event and a keypress event to be triggered.

To solve this problem, this code snippet keeps track of whether the last key pressed was a space and ignores the next click if it was.

It's worth mentioning that some code related to 'Space' in the question was never used and has been removed in this snippet.

<body>
  <div id="text"></div>
  <button id="a" onClick="if (!lastKeyWasKeypressedSpace) {keyClick(this.id);} else {lastKeyWasKeypressedSpace = false;}">a</button>
</body>
<script>
  let lastKeyWasKeypressedSpace = false;
  window.addEventListener('keypress', function(e) {
    keyClick(e.key);
    lastKeyWasKeypressedSpace = e.key == ' ';
  });

  function keyClick(key) {
    document.getElementById('text').textContent = document.getElementById('text').textContent + key;
  }
</script>

Furthermore, it is important to determine the action to take when the enter key is pressed, although that aspect is not covered in this question.

ADDITION:

While I cannot replicate the exact scenario described in the comments (regarding using the button after keyboard and space input), one suggestion is to replace buttons with simple div elements.

This approach avoids issues with special characters like space [and enter] triggering onclick events.

Here is a basic example showcasing this method:

<style>
  .key {
    background-color: #eeeeee;
    border: solid 1px black;
    bordeer-radis: 5px;
    display: inline-block;
    padding: 0 5px 2px 5px;
  }
  
  .key:hover {
    background-color: #cccccc;
  }
</style>

<body>
  <div id="text"></div>
  <div id="a" onClick="keyClick(this.id);" class="key">a</div>
</body>
<script>
  window.addEventListener('keypress', function(e) {
    keyClick(e.key);
  });

  function keyClick(key) {
    document.getElementById('text').textContent = document.getElementById('text').textContent + key;
  }
</script>

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

What is the best way to send a POST request with an array containing multiple objects within it?

Unique Context Currently, I am expanding my knowledge of JavaScript by working on a REST API project using node.JS and express. I have encountered a challenge while attempting to parse an array of objects that contains nested arrays of objects. Below is a ...

What is the best way to organize objects by their respective dates?

I am retrieving data from a database and I would like to organize the response by date. I need some assistance in grouping my data by date. Below is an example of the object I have: var DATA = [{ "foodId": "59031fdcd78c55b7ffda17fc", "qty" ...

Detecting page scrolling in Angular can be a challenging task

Having some issue with detecting scroll events in Angular. Here's the code snippet: @HostListener("window:scroll", []) onWindowScroll() { console.log("hello"); } Can anyone spot what I'm doing wrong? ...

html div elements may not align correctly

Currently, I am in the process of coding a website that contains numerous images. To assist me in organizing and arranging these images, I have turned to angularjs. Initially, everything was progressing smoothly until this issue arose: https://i.sstatic. ...

What is the best way to place a floating elastic div on top of an elastic background and ensure that the div stays in place?

Looking for some creative input here. Don't have a specific question in mind, but open to ideas. Just to clarify, I want both the floating div and the background to resize as the window size changes, while keeping the div in the same position on top ...

Tips for ensuring the server only responds after receiving a message from the client in a UDP Pinger system using sockets

I am in the process of developing a UDP pinger application. The objective is for the client to send a message (Ping) and receive pong back 10 times. However, the challenge lies in sending the messages one at a time instead of all together simultaneously. T ...

Using Bootstrap 5 in conjunction with Electron is causing compatibility issues

This is my first venture into creating an electron app and I wanted to add some styling using bootstrap 5. Here's what I did: (1) I used npm i --save bootstrap jquery popper.js to install the necessary modules (2) Created a main.scss file including ...

I am having trouble getting all the HTML content to properly display in the GitHub zip file

I am encountering an issue where the index.html file is not displaying the navigation or images as expected. For reference, the project can be found at https://github.com/LawlietBlack/Persona-4-Golden-Guide If there is a more appropriate place to ask this ...

Looking for a way to choose a button with a specific class name and a distinct "name" attribute using jquery?

I am currently working on developing a comment system. As part of this system, I want to include a toggle replies button when a user posts a reply to a comment. However, I only want this button to be displayed if there are no existing replies to the commen ...

The specified type 'ReturnType' mandates one type argument. Error code: ts(2314)

After transitioning from Flow to Typescript, I have encountered errors while converting some of the codebase. Most of the issues have been resolved using the Utility-Types package, but I am stuck with the code below without any helpful documentation or ans ...

Original state of class name is restored upon change

I'm currently working on creating a Lightbox-style effect using CSS and Javascript. The idea is to change the classname of an element (OverlayContainer) to toggle between a normal background and a darker overlay. However, I've run into an issue w ...

What is the method for extracting latitude and longitude values individually from JSON data?

Upon receiving the JSON response from the Google Maps API stored in a variable named 'obj', I noticed that alerting obj.name returns "Pancakes on the Rocks". To access the icon, I can use obj.icon. However, I am struggling to retrieve separate va ...

Using setTimeout within a ForEach loop does not adhere to the specified milliseconds for waiting

Although ForEach console.log's very fast, I am looking to introduce a delay of 8 seconds before logging the next item in Set. I experimented with setTimeout but it doesn't appear to output at the precise milliseconds specified. const completedIds ...

What steps should be followed to set up Selenium WebDriver to accept command line options using Node.js?

I'm currently working with Selenium WebDriver through Node.js and I have a set of resources that I'm not sure how to interpret for my specific objective (here and here). At the moment, all my tests are running successfully as intended but now I w ...

Streaming video between web browsers using WebRTC and CORS

The demo of WebRTC (https://webrtc.github.io/samples/src/content/capture/video-video) showcases the ability to stream one video's contents to another using video.captureStream(). However, I'm encountering issues when attempting this across differ ...

I just made an ajax call. Now, how should I proceed with formatting the data that was returned

The ajax request below is functional, but not without its challenges. Working with HttpContext has proven to be difficult, as even Context.Response.Clear() does not seem to have any effect. How can I output only the desired content without any extra infor ...

Creating a stylish border around an image using a JavaScript function

I am interested in creating a JavaScript function called addborder(y) that will add a yellow border to an image. This experiment aims to explore the process of manipulating images using JavaScript. <!--HTML--> <img id="img" src="http://pre01.d ...

Applying a distinct CSS style to the final entry of each list item

Is there a way for me to assign a different style for the last entries in my code? <?= $k % 2 == 1 ? 'news-figure' : 'news-figure-b' ?> ...

Implementing Google Calendar access token in JavaScript: A practical guide

I have a question about Google Calendar and I'm hoping you can assist me. I currently have an access_token from Google Calendar that has been stored in the localStorage. const googleAccessToken = e.vc.access_token; localStorage.s ...

Retrieving Information from Ajax Call Using Python

I am struggling to figure out how to retrieve data from an Ajax request in my JavaScript code within a Python Flask application. The Ajax request I am working with does not involve jQuery. I have attempted using request.form.get() and request.get_json() i ...