Manipulating the Caret in Contenteditable Elements
Problem: How can you efficiently move the caret to the end of a contenteditable element, mimicking the behavior found in Gmail's notes widget?
StackOverflow offers solutions that work for input elements but fail with contenteditable elements. This article presents a tailored approach specifically for contenteditable elements.
Solution:
For browsers supporting contenteditable, the following JavaScript function can accomplish the desired caret movement:
function setEndOfContenteditable(contentEditableElement) { // Determine browser support var range, selection; if (document.createRange) { // Modern browsers range = document.createRange(); range.selectNodeContents(contentEditableElement); range.collapse(false); // Collapse to end of range selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range); } else if (document.selection) { // IE 8 and lower range = document.body.createTextRange(); range.moveToElementText(contentEditableElement); range.collapse(false); // Collapse to end of range range.select(); } }
Usage Example:
To move the caret to the end of an element with the ID 'txt1':
elem = document.getElementById('txt1'); setEndOfContenteditable(elem);
The above is the detailed content of How to Move the Caret to the End of a ContentEditable Element?. For more information, please follow other related articles on the PHP Chinese website!