Home > Web Front-end > JS Tutorial > How to Move the Cursor to the End of a ContentEditable Element?

How to Move the Cursor to the End of a ContentEditable Element?

Patricia Arquette
Release: 2024-11-11 01:50:02
Original
970 people have browsed it

How to Move the Cursor to the End of a ContentEditable Element?

Move Cursor to End of Contenteditable Entity

Ever encountered the need to position the cursor to the end of a contenteditable element, akin to the functionality seen in Gmail's notes widget?

The Solution

For contenteditable elements, Geowa4's solution is not applicable. A tailored approach is necessary:

function setEndOfContenteditable(contentEditableElement) {
  var range, selection;
  if (document.createRange) {
    // Modern browsers
    range = document.createRange();
    range.selectNodeContents(contentEditableElement);
    range.collapse(false);
    selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
  } else if (document.selection) {
    // IE 8 and below
    range = document.body.createTextRange();
    range.moveToElementText(contentEditableElement);
    range.collapse(false);
    range.select();
  }
}
Copy after login

To employ it, simply follow the code example:

var elem = document.getElementById("txt1");
setEndOfContenteditable(elem);
Copy after login

Compatibility

This solution is compatible with all major browsers that support contenteditable.

The above is the detailed content of How to Move the Cursor to the End of 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