JSFiddle - React, Tailwind, and code Playground
HTML
<textarea id="foo">abcdef
ghijkl
mnopqr
stuvwx</textarea>
<br/>
<button id="home">Home</button>
<button id="up">Up</button>
<button id="end">End</button><br/>
<button id="left">Left</button>
<button id="down">Down</button>
<button id="right">Right</button><br/>
CSS
textarea {height: 100px; width:100px;}
button {border: 1px sold #000000; height:50px; width: 50px;}
JavaScript
var elm = document.getElementById('foo');
elm.selectionStart = elm.selectionEnd = 10;
elm.focus();
document.getElementById('home').addEventListener('click',
function () {homeKey(elm); elm.focus();}
);
document.getElementById('end').addEventListener('click',
function () {endKey(elm); elm.focus();}
);
document.getElementById('up').addEventListener('click',
function () {arrowUp(elm); elm.focus();}
);
document.getElementById('down').addEventListener('click',
function () {arrowDown(elm); elm.focus();}
);
document.getElementById('left').addEventListener('click',
function () {arrowLeft(elm); elm.focus();}
);
document.getElementById('right').addEventListener('click',
function () {arrowRight(elm); elm.focus();}
);
function homeKey(elm) {
elm.selectionEnd =
elm.selectionStart =
elm.value.lastIndexOf(
'\n',
elm.selectionEnd - 1
) + 1;
}
function endKey(elm) {
var pos = elm.selectionEnd,
i = elm.value.indexOf('\n', pos);
if (i === -1) i = elm.value.length;
elm.selectionStart = elm.selectionEnd = i;
}
function arrowLeft(elm) {
elm.selectionStart = elm.selectionEnd -= 1;
}
function arrowRight(elm) {
elm.selectionStart = elm.selectionEnd += 1;
}
function arrowDown(elm) {
var pos = elm.selectionEnd,
prevLine = elm.value.lastIndexOf('\n', pos),
nextLine = elm.value.indexOf('\n', pos + 1);
if (nextLine === -1) return;
pos = pos - prevLine;
elm.selectionStart = elm.selectionEnd = nextLine + pos;
}
function arrowUp(elm) {
var pos = elm.selectionEnd,
prevLine = elm.value.lastIndexOf('\n', pos),
TwoBLine = elm.value.lastIndexOf('\n', prevLine - 1);
if (prevLine === -1) return;
pos = pos - prevLine;
elm.selectionStart = elm.selectionEnd = TwoBLine + pos;
}