A javascript function selects a certain word in a textarea using .setSelectionRange(). In Firefox, the textarea automatically scrolls down to show the selected text. In Chro
Based on the idea from @naXa and @Valeriy Katkov, I refined the function with less bug. It should work out of the box (It's written with TypeScript. for JavasCript, just remove the type declariation) :
function scrollTo(textarea: HTMLTextAreaElement, offset: number) {
const txt = textarea.value;
if (offset >= txt.length || offset < 0)
return;
textarea.scrollTop = 0; // Important, so that scrollHeight will be adjusted
textarea.value = txt.substring(0, offset);
const height = textarea.scrollHeight;
textarea.value = txt;
textarea.scrollTop = height - 40; // Margin between selection and top of viewport
}
Usage:
let textarea, start, end;
/* ... */
scrollTo(textarea, start);
textarea.focus();
textarea.setSelectionRange(start, end);