What is the reason behind the caret in the input being set at the beginning when using focus() without a timeout?

I am currently exploring the implementation of keyboard navigation between multiple input fields using VueJs.

Here is how the template is set up...

<div v-for="(note, index) in notes" 
         :key="index" ref="notex" class="input-wrapper" id="input-wrapper"
         :class="{ 'focused': note.isFocused }">
              <input v-model="note.value" 
                     spellcheck="false" class="input" v-on:keydown.enter="createNextNote()"
                     :id="note.value ? '' : 'empty-input'" 
                     @focus="note.isFocused = true" @blur="note.isFocused = false">
</div>

The function that executes when clicking the "ArrowUp" key (a global listener has been set up for this)

        moveUp() {
            const index = parseInt(Object.keys(this.notes).find(key => this.notes[key].isFocused));

            if (!this.notes[index - 1]) {
                return;
            }

            this.notes[index].isFocused = false;
            this.notes[index - 1].isFocused = true;

            let requiredInput = this.$refs['notex'][index - 1].firstChild;
            
            // The reason behind using a timeout here?
            setTimeout(() => requiredInput.focus(), 1);
        },

Focusing on the timeout functionality.

My confusion lies in understanding the difference between employing the timeout feature and not.

Simply calling requiredInput.focus() positions the focus in the input field but places the caret at the start.

However, by utilizing a timeout as shown above, the caret aligns behind the existing text - achieving the desired outcome.

I attempted to utilize VueJs's nextTick method, however, it results in the same positioning as without the timeout - placing the caret before the input value.

Can someone provide clarity on this distinction, please?

Answer №1

Soon after, I discovered the root of the issue. The problem stemmed from how I configured the event listeners for key inputs...

        mounted() {
           window.addEventListener('keyup', function (e) {
               if (e.code === 'ArrowUp') {
                   app.moveUp();
               }
           });
        }

The crux of the matter was that I mistakenly set it to detect "keyup" instead of "keydown". This caused the input field to inadvertently shift when a "keydown" event occurred, leading to the cursor jumping to the beginning of the input value upon release.

In addition, I relocated the event listeners to the template itself and implemented preventDefault() to curb the default actions of the input fields.

<input v-on:keydown.up="moveUp($event)" v-on:keydown.down="moveDown($event)">

moveUp(e) {
   e.preventDefault();
   // Carry on with the remaining tasks
}

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

convert a list of options into a dropdown selection menu

Is there a way to turn a regular menu into a dropdown menu for small devices without modifying the HTML code? I have a responsive design, but I'm not sure how to add that 'hamburger menu' style. Note: I am unable to make changes to the HTML ...

Issues with Javascript functionality in Internet Explorer and Google Chrome

Hello everyone, I'm experiencing an issue with a thumb image link swapping out on hover. Oddly enough, it seems to work perfectly in Firefox and Safari, but it's not showing up on IE and Chrome. As I am relatively new to Javascript, I may be over ...

Tips for setting environmental variables to match ID values in html documents

In my API reference call, I have stored the key in a separate file and protected it using .gitignore since I am using GitHub. However, I am facing an issue on how to transfer that key from my JavaScript file into the HTML data-key attribute using a variab ...

How can a variable that is potentially undefined be converted to lowercase in Node.js?

My latest project involves developing a discord.js bot with commands that can take different parameters like mc!start vanilla, mc!start tekkit. However, the bot is designed to handle only singular string entries. So, when a user inputs just mc!start with ...

Creating an animated background slide presentation

After creating a button group, I wanted the background of the previous or next button to move/slide to the selected one when the user clicks on it. I achieved this effect using pure CSS and simply adding or removing the 'active' class with jQuery ...

Generating a list of items to buy using a JSON document

So here's the json file I'm working with: [ {"task":"buy bread","who":"Sarah","dueDate":"2023-10-18","done":false}, {"task":"clean car","who":"David","dueDate":"2023-08-30","done":true}, {"task":"write report","who":"Jenny","dueDate":"2023-09 ...

Utilizing Regular Input with Material-UI's Autocomplete Feature

Is there a way to replace TextField with a regular input in an Autocomplete? ...

Unable to view specific routes by name

Sorry, but I just can't seem to figure this out. I set up routes in a separate JavaScript file, imported it into a new router that I mounted in Vue. In the Vue devtools, my named routes are visible, but where the RouterView should be in the HTML is no ...

Javascript is not functioning properly when making an ajax call

Having a bit of trouble with JavaScript not working after an Ajax call. Everything functions normally until new data is fetched from the database or an Ajax call is made. The issue seems to be that the JavaScript doesn't load properly. Any help would ...

Making Cross-Origin Requests using jQuery's Ajax function and PHP

I've attempted numerous times to make this function properly, but for some reason, I just can't seem to figure it out. Initially, everything was working flawlessly for a few requests, and then out of the blue, it stopped functioning. Below is t ...

Learn how to retrieve Firebase documents in reverse chronological order using React-firebase-hooks

I'm working on a chat app and I believe that Firebase Cloud Firestore queries documents in ascending order. I have come across solutions online that suggest initializing values as negatives, but since I am dealing with timestamp objects that correspon ...

Evaluating the use of promise in Angular using Jasmine testing

I'm currently troubleshooting whether a method with a promise is being properly called Below is the snippet of my controller code: app.controller('StoresListController', function ($scope, StoresService) { $scope.getStores = function ( ...

Terminate a targeted recipient following the completion of the on event

I am currently running a node service with socket.io and utilizing an event emitter to send updates based on user context. For example, context A may have users 1, 2, and 3 while context B has users 4 and 5. Once a successful connection is established wit ...

What is the best way to retrieve a single document from MongoDB by using the URL ID parameter in JavaScript?

I'm currently working on a movie app project and have defined my movie Schema as follows: const movieSchema = new mongoose.Schema({ name: { type: String, required: true }, genre: { type: String, required: tr ...

A simple way to set a button as active when clicked in a form element

Is there a way to activate the input button with an Onclick event? <div class="paForm-right"> <form onsubmit="" name="form1" id="form1" method="post"> <input type="submit" class="paForm-choose" id="paForm-bottom-vk" value="Visi ...

Leverage Webpack's File-Loader to Import Images

I have implemented Webpack in my React application. I have added 'File-loader' & 'Url-loader' to my webpack configuration. But I am uncertain about how to connect images to my components. I'm storing the image source ('s ...

Best practices for integrating JavaScript with PHP and MySQL

When it comes to inserting data into a MySQL database from JavaScript, I typically use AJAX with jQuery's $.POST function and PHP's mysqli function. This allows me to send the data to a PHP script which then inserts it into the database. Here is ...

Issue with retrieving date from MySQL column being a day behind in JavaScript (Node.js)

I currently have a Node.js server up and running as the API server for a service that I am developing for a company. The dates stored in the MySQL server that it connects to are related to event start times. Insertion of these dates is flawless, and when ...

What are the best ways to incorporate mistakes into my JavaScript mortgage calculator?

I am struggling to set up my calculator so that it triggers an error message if the APR goes over 25% or falls below 0. Also, the Loan Term should be greater than 0 and less than or equal to 40, otherwise display an error message. I have attempted differen ...

The functionality of the Angular ng-bind-html directive may be unreliable in specific scenarios

I've exhausted all the solutions found on stack overflow but still haven't found a solution. Using angular 1.4.4 and ng-repeat directive, I am attempting to display a HTML comment inside a table row. A sample comment looks like 'Test commen ...