Firefox textarea scrolling made simple: Now that
https://bugzilla.mozilla.org/show_bug.cgi?id=303713 is fixed, a much
simpler approach to textarea scrolling is possible (recall that the
problem is to scroll to a given textarea's selection - see
..selectionStart/End). We can make use of the fact that FF scrolls the
textarea to the caret if there is a text change (text change implies
that any prior selection is collapsed). Some notes follow the demo.
Csaba Gabor from Vienna
<html>
<head><title>Textarea scrolling</title></head>
<body bgcolor=yellow style=margin-left:.4in>
<form action='' method=get>
<textarea id=ta name=ta>
This is some initial
text for the purpose of
searching in the textarea
to see how scrolling to a
non currently showing section works
</textarea><br>
Sear<u>c</u>h term: <input type=text id=tbNeedle
name=tbNeedle accesskey=c>
<button type=button accessKey=s
onclick="search(elem('tbNeedle').value,'ta')"
Te<u>s</u>t</button>
</form>
Suggestion:<br>
(1) Don't put focus in the textarea<br>
(2) First search for 'the textarea' (without quotes)<br>
(3) Then search for 'This'
<script type='text/javascript'>
function elem(id) { return document.getElementById(id); }
function search(needle,haystack,start) {
var i, element = elem(haystack);
index = element.value.indexOf(needle,start||0);
if (index<0) {
window.status = "Not found: " + needle;
window.setTimeout (function(){window.status=''}, 4000); }
else {
element.setSelectionRange((i=index+needle.length)-1,i);
var ev = document.createEvent ('KeyEvents');
ev.initKeyEvent('keypress', true, true, window,
false, false, false, false, 0,
element.value.charCodeAt(i-1));
element.dispatchEvent(ev); // causes the scrolling
element.setSelectionRange(index, i);
}
}
</script>
</body></html>
Notes:
(A) You might wish to explicitly test for (!index) in which case you
could have:
else if (!index) {
element.value=element.value; // this line has value
element.setSelectionRange(0, needle.length); }
The middle line will cause the scrolling to be reset. You could
instead use:
element.scrollTop = 0; element.scrollLeft = 0;
(B) The reason for not putting focus into the textarea is on account
of
https://bugzilla.mozilla.org/show_bug.cgi?id=332424: textarea
selections made (via javascript) before the textarea has received focus
will be visible even though the textarea does not have focus, which
allows for simpler search changes.