Home > Web Front-end > JS Tutorial > How to Programmatically Set the Caret Position in a ContentEditable Element?

How to Programmatically Set the Caret Position in a ContentEditable Element?

Barbara Streisand
Release: 2024-12-05 19:20:11
Original
912 people have browsed it

How to Programmatically Set the Caret Position in a ContentEditable Element?

Setting Caret Position in a Content Editable Element

Setting the caret position in a contenteditable div can be achieved using the Range and Selection objects. Here's how to set the caret to a specific position within the element:

Code:

function setCaret() {
    var el = document.getElementById("editable")
    var range = document.createRange()
    var sel = window.getSelection()
    
    range.setStart(el.childNodes[2], 5)
    range.collapse(true)
    
    sel.removeAllRanges()
    sel.addRange(range)
}
Copy after login

Explanation:

  • el represents the contenteditable element.
  • range is the Range object used to specify the caret position.
  • sel is the Selection object used to manipulate the selection.
  • setStart() sets the start of the range to the specified node and offset (el.childNodes[2] and 5, respectively).
  • collapse() collapses the range to a single point at the start position.
  • removeAllRanges() removes any existing selections.
  • addRange() adds the created range to the selection.

Example:

Consider the following HTML:

<div>
Copy after login

When you click the "focus" button, the JavaScript function setCaret() is invoked, placing the caret at the fifth character of the second line of text.

The above is the detailed content of How to Programmatically Set the Caret Position in a ContentEditable Element?. 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