How can I determine in JavaScript if the Backspace key is being long pressed on iOS or Android devices?

In the process of developing a web application using Vue.js, I encountered an issue with detecting long presses of the Backspace key on desktop keyboards (Windows PCs specifically). On desktop, the event triggers multiple times as long as the Backspace key is held down. However, on mobile devices, it only fires once even if the Backspace key is held for an extended period.

My goal is to have the focus shift to the previous field when all text is cleared from the current field, and eventually have the cursor move to the first field once all fields are empty.

While I've managed to address this on desktop, I'm facing difficulties with mobile platforms like Android and iOS.

https://i.stack.imgur.com/1gfWQ.png

HTML:

<input 
    @keydown="onKeydown(key, $event)"
    @paste="onPasteEvent(key, $event)"
    @keyup="onKeyup(key, $event)"
    @click="onInputClick(key, $event)"
    type="text" 
    :name="'input' + key"
    v-model="code[key]"
    :maxlength="(key === 0 ? 6 : 5)"
>

Keydown handler:

 onKeydown(key, event) {
        let input = document.querySelector('input[name="input'+ key +'"]');

        switch (event.key) {
            case 'Backspace':
                // If not in first field and no text before the cursor 
                // position; focus the previous field.
                if (key > 0 && !this.getPrevWord(input)) {
                    this.moveCursorLeft(key);
                }
                break;

            case 'Delete':
                // If not in last field and no text after the cursor position;
                // focus the next field.
                if (key < (this.inputs - 1) && !this.getNextWord(input)) {
                    this.moveCursorRight(key);
                }
                break;
        }
 },

Answer №1

Give this a shot:

onKeyPress(key, event) {
        let userInput = document.querySelector('input[name="userInput'+ key +'"]');

        switch (event.keyCode) {
            case 8:

                // Check if not in the first field and there is no text before the cursor position; then focus on the previous field
                if (key > 0 && !this.getPreviousText(userInput)) {
                    this.moveCursorToLeft(key);
                }
                break;

            case 46:
                // If not in the final field and there is no text after the cursor position; then focus on the next field
                if (key < (this.totalInputs - 1) && !this.getNextText(userInput)) {
                    this.moveCursorToRight(key);
                }
                break;
        }
 },

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

Error: Issue determining the type of variable. Unable to eliminate type 'any'

I am trying to load some widgets from a template object (possibly JSON in the future). Here's an example: type RectangleTemplate = { name: 'Rectangle'; props: { width: number; height: number; } }; type ButtonTemplate = { nam ...

Organize and categorize items

I need help sorting an object displayed below. My goal is to calculate the sum of all rating properties for each object, and then sort the objects based on the highest total rating. For instance, if the total rating for Intro 1 is 7 and for Intro 2 is 3, ...

Errors persist with Angular 2 iFrame despite attempts at sanitization

Attempting to add an iFrame within my Angular 2 application has been challenging due to the error message that keeps popping up. unsafe value used in a resource URL context The goal is to create a dynamic URL to be passed as a parameter into the iFrame ...

Is iterating over an array of objects the same as avoiding repetitive code?

Update: Incorporating JavaScript with the three.js library. To streamline our code and prevent repetition, we utilize loops. However, in this specific scenario, the for loop is not functioning as expected compared to six similar lines that should achieve ...

Error with JSON data from the Twitch TV API

I am having trouble with the Twitch API. When a streamer is live, I work with the "Stream" property, but if they are not streaming, I need to refer to another link. I use the getJSON function to fetch the necessary API link and work with it. However, my lo ...

Tips for positioning a grid at the center of a MaterialUI layout

I am struggling to position 3 paper elements in the center of both the vertical and horizontal axes on the screen. Despite applying various CSS rules and properties, the height of the HTML element consistently shows as 76 pixels when inspected in the con ...

Using jQuery to include a sub-object in the "data" object for each AJAX request made on the webpage

Is there a way to enhance the functionality of jQuery.ajax by including a static sub-data object in every ajax request automatically? For instance, for an ajax request like this: jQuery.ajax({ url: 'request_file.php', data: { da ...

Incorporating telepat-io into a Java Struts enterprise solution

Our J2EE enterprise application, built on Java Struts, has a static front end. Our team's architect has opted to enhance the user authentication by incorporating Ajax and JavaScript functionalities using telepat-io. The project is currently managed w ...

Error Encountered: Unable to establish server connection with NodeJS Express JS and Mongo database

Can you help decipher this error message? $ pm2 logs [TAILING] Tailing last 15 lines for [all] processes (modify the value with --lines option) /home/tealou/.pm2/pm2.log last 15 lines: PM2 | 2017-03-29 07:25:45: Application [www] with id [0] and pr ...

I can't seem to get db.collection.findOneAndUpdate() to work properly when using the

User Data { "_id" : ObjectId("60c012cc35fd3c596d61e72d"), "tags" : [ "react", "node", "js" ], "title" : "This is the updated title", "description" : "I am a skil ...

The interfaces being used in the Redux store reducers are not properly implemented

My Redux store has been set up with 2 distinct "Slice" components. The first one is the appSlice: appSlice.ts import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import type { RootState } from "./store"; export interface CounterState { value ...

Each time the page is reloaded, the animation's frames per second (fps

In my project, I have two main pages: 'index' and 'about'. The 'about' page includes a cool animation that you can check out here. The issue I'm facing is that when I navigate from the 'index' page to the &apos ...

What is the process for extracting content from CSS comments or annotations in a stylesheet?

Here's an interesting concept: allowing users to define a set of CSS rules with annotations. For example: /* @name Page style */ body { font: 16px/1.5 Arial; /* @editable */ background-color: #fff; /* @editable */ } /* @name Section header */ ...

Using Vue/Nuxt, you can schedule the execution of a function on a specific page by employing either $nextTick or

I have a function that I want to call every 10 seconds on my page when it is mounted. However, even after leaving the page, the function continues to run indefinitely. mounted() { if(this.user_authenticated) { this.$nextTick(function () ...

I desire for both my title and navigation bar to share a common border-bottom

As I embark on my journey into the world of HTML and CSS, my knowledge is still limited. Despite trying various solutions from similar queries, none seem to resolve my specific issue. What I yearn for is to have both my title and navigation bar share the s ...

Is there a way for me to implement this code to achieve the functionality shown in the demo link

$('select').change(function() { var sum = 0; var sum = parseInt($('select[name="bathrooms"]').val() * 25) + parseInt($('select[name="bedrooms"]').val() * 8); $("#sum").html(sum); }); <script src="https://ajax.googleap ...

Why isn't useEffect recognizing the variable change?

Within my project, I am working with three key files: Date Component Preview Page (used to display the date component) useDateController (hook responsible for managing all things date related) In each of these files, I have included the following code sn ...

How to Use Conditional In-Line CSS for Internet Explorer and Other Browsers

After inspecting the source code for this website, I noticed a cool feature where the page changes based on your scrolling position. It creates a visually appealing effect. Upon further examination of the source in FireFox, I observed the use of -webkit-t ...

What is the inner workings of stream.Transform in Node.js?

Recently, I stumbled upon a code snippet on a blog showcasing the usage of the stream Transform class to modify data streams and display the altered output. However, there are certain aspects of this code that leave me puzzled. var stream = require(&apos ...

Developing a vanilla JavaScript web component with distinct HTML and JavaScript files

As I delve into creating vanilla JS web-components, I am exploring methods to keep the template HTML separate from the JS file, ideally in a distinct HTML file. I have examined various implementations of native JS web-component setups found notably here, ...