JSFiddle - React, Tailwind, and code Playground
HTML
<input type="text" value="ammmmmmm4545646344r6sf46sdfRob W" id="inputElement" />
JavaScript
/* @name caretAtEnd
* @description Places caret at the end
* @param elem DOM element
* @param focus boolean, optional. If true, the element will be focused.
*/
function caretAtEnd(elem, focus){
var value = elem.value;
//Add an extra character to the input field (necessary for this method)
// An additional advantage is that the caret automatically moves to the end
elem.value = elem.value + ".";
try {
// Create and simulate/trigger a [Backspace] keypress event.
var evt = document.createEvent("KeyboardEvent");
evt.initKeyEvent("keypress", 1, 1, null, 0, 0, 0, 0, 8, 0);
elem.dispatchEvent(evt);
} catch(e){
//The current key event is not supported yet. Change back the value
// In some browsers, the caret is at the end after executing this code.
elem.value = value;
}
//Optionally, Focus on the element
if(focus) elem.focus();
}
var element = document.getElementById("inputElement"); //Important: Get the DOM element!
caretAtEnd(element, true);