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!