Home > Web Front-end > JS Tutorial > How to Reliably Place the Cursor at the End of a Text Input Element in JavaScript?

How to Reliably Place the Cursor at the End of a Text Input Element in JavaScript?

Linda Hamilton
Release: 2024-11-30 06:03:11
Original
898 people have browsed it

How to Reliably Place the Cursor at the End of a Text Input Element in JavaScript?

Place Cursor at End of Text Input Element in JavaScript

Placing the cursor at the end of a text input element through JavaScript is a straightforward task, especially after focus is set to the element. Let's explore the most efficient and straightforward approach:

The following code snippet provides a simple yet effective solution:

this.selectionStart = this.selectionEnd = this.value.length;
Copy after login

This line calculates the length of the input value and sets both the start and end cursors to that position. This method works in most major browsers.

However, certain browsers exhibit quirks that necessitate a more comprehensive solution:

setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
Copy after login

In this code snippet, a setTimeout() is utilized to address potential browser inconsistencies. It sets the cursor position to an arbitrarily large number (e.g., 10000), ensuring that it is beyond the end of the input text, essentially placing it at the end.

Additionally, you can utilize jQuery to set the focus listener:

$('#el').focus(function(){
  var that = this;
  setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
});
Copy after login

The above is the detailed content of How to Reliably Place the Cursor at the End of a Text Input Element in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template