Home >Web Front-end >JS Tutorial >How Can I Set the Cursor Position in a Text Area Using jQuery?

How Can I Set the Cursor Position in a Text Area Using jQuery?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-08 15:28:11922browse

How Can I Set the Cursor Position in a Text Area Using jQuery?

Setting Cursor Position in a Text Area with jQuery

Problem:

How can you set the cursor position within a text area using jQuery? You have a text area with existing content, and you want to automatically position the cursor at a specific offset when the field receives focus.

Solution:

For jQuery, the following code snippet can be used to achieve this functionality:

$.fn.selectRange = function(start, end) {
    if(end === undefined) {
        end = start;
    }
    return this.each(function() {
        if('selectionStart' in this) {
            this.selectionStart = start;
            this.selectionEnd = end;
        } else if(this.setSelectionRange) {
            this.setSelectionRange(start, end);
        } else if(this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    });
};

With this function, you can use the following syntax:

$('#elem').selectRange(3,5); // select a range of text
$('#elem').selectRange(3); // set cursor position

This allows you to set the cursor position within the text area, whether you want to select a range of text or simply position the cursor at a specific offset.

Additional Resources:

  • [JsFiddle Demo](https://jsfiddle.net/ywkf09w4/)
  • [JsBin Demo](https://jsbin.com/xewotib/edit?html,console,output)

The above is the detailed content of How Can I Set the Cursor Position in a Text Area Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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