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
Patricia ArquetteOriginal
2024-11-11 01:50:021013browse

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();
  }
}

To employ it, simply follow the code example:

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

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!

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