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

React ES6 SystemJS encountered an unforeseen token error that couldn't be caught

Even though I have imported react and react-dom using the System.config setup below, I am still encountering the error mentioned here: Uncaught (in promise) Error: Unexpected token <(…) Here is the HTML structure: <!DOCTYPE html> <html l ...

Error: Unable to split function. Attempting to retrieve API response via GET request using ngResource

I am trying to retrieve some data from an API using ngResource by utilizing the get method. Even though I have set up a factory for my resource, when implementing it in my controller, I encounter an error stating URL.split is not a function. I'm stru ...

Discover the proper technique to display an error message in cases where no data is detected during the filtering process

I'm currently working on a component that involves search filtering and dropdown filtering. The filtering functionality is working fine, but I'm struggling to determine where to display an error message if no data is found during the filtering pr ...

Unable to invoke a custom hook within another custom hook in a React application

I've developed a React application using create-react-app. Currently, I'm working on creating a custom hook that integrates with the Microsoft Authentication Library (MSAL). MSAL provides a custom React hook that I want to utilize within my own ...

Display a message stating "No data available" using HighCharts Angular when the data series is empty

My Angular app utilizes Highchart for data visualization. One of the requirements is to display a message within the Highchart if the API returns an empty data set. I attempted a solution, but unfortunately, the message does not appear in the Highchart a ...

Javascript navigation menu failing to accurately display all pages

As I continue to enhance my website at , I have encountered an issue with the menu functionality. The menu is dynamically generated through JavaScript, scanning a folder for pages and populating them into an array. While this system functions smoothly ove ...

What is the process for retrieving a detached element?

In the game, I'm looking to provide a "start again" option for users when they lose. The .detach() method comes in handy for hiding the button initially, but I'm struggling to make it reappear. Some solutions suggest using the append() method, bu ...

Highest Positioned jQuery Mobile Section

Requesting something a bit out of the ordinary, I understand. I currently have a jQueryMobile page set up with simplicity: <div data-role="page" class="type-home" id="home"> <div data-role="header" data-theme="b"> <h1>Our To ...

Customize Your Lightbox Fields with DHXScheduler

In my JSP application for exam timetabling, I have integrated DHXScheduler and customized the lightbox to display additional information about exams using my own fields. The EventsManager class is responsible for managing events by saving, creating, and r ...

Filtering the inner ng-repeat based on the variable of the outer ng-repeat

I have a collection of elements. Some of these elements are considered "children" of other elements known as "parent" elements. Instead of rearranging the JSON data received from the server, I am attempting to filter the results within the ng-repeat loop. ...

What could be causing my array to update when the method is called live but not during unit tests?

One of my methods is called toggleSelect which adds and removes items from an array named selectedItems. This method functions perfectly when I test it live in the browser. However, when running unit tests, it does not seem to work as expected. Despite cal ...

What is the best way to reset local state after triggering a success action in Redux Saga?

I'm looking to reset my component state after a successful call in redux saga. Is there a way to achieve this? Currently, I am using the component state to track my input value. this.state = { department: '', }; The solution I have im ...

Tips for executing a <script> whenever the properties of a component are modified

Can I automatically run a <Script/> every time the props of a react/nextjs component change? I'm currently converting markdown files to HTML using marked and, before rendering the HTML, I want to include a [copy] button on each <pre> bloc ...

Display a sneak peek on a separate tab

I have an editor on my website where users can input and edit their own HTML code. Instead of saving this to a database, I want to display the current user's HTML code in a new window using JavaScript. How can I achieve this without storing the code p ...

Are there any lodash functions available for removing an array that matches another array from the main array?

I currently have two arrays named available and selected, each containing certain values. I also have another array called finalAvailable where I want to include all items from the available array except those that are already present in the selected array ...

Tips for styling a button upon being clicked

Is there a CSS technique to make a button change color when clicked with the mouse? I am aware of using ':hover' for changing color, but I need something specific to a left mouse click. I want the same functionality as a standard button but with ...

Is There a Way to Abandon a route and Exit in Express during a single request?

In order to ensure proper access control for the application I was developing, I structured my routing system to cascade down based on user permissions. While this approach made sense from a logical standpoint, I encountered difficulties in implementing it ...

Having difficulty accessing the ::after element on Firefox when attempting to click

I've encountered an issue with my HTML and CSS code - it functions perfectly on Chrome, yet behaves differently on Firefox. button#groupToggle { background: 0 0; border: 1px solid #e6e6ed; color: #222; float: none; margin: 0 0 ...

Implementing Event Handlers for Multiple Textareas Using Jquery on a Webpage

The functionality of my script is exactly how I want it to be, but I am facing an issue when trying to replicate it on a page. The jQuery code manipulates textarea boxes based on button clicks, however, I now need each textarea box to have its own set of b ...

Working with AngularJS: Accessing a JSON file from the local directory

The answers to my previous questions on this topic have not been satisfactory. It seems that most examples and tutorials for AngularJS online always define tiny JSON arrays directly inside the JavaScript code... So, let's simplify things with a basi ...