James
James

Reputation: 6509

Extending text selection using Javascript

If a user selects a portion of text, I'd like to extend that selection to the beginning of the first line and to the end of the last line if they select in the middle.

What's the best way to accomplish this?

Upvotes: 0

Views: 416

Answers (1)

lazyboy
lazyboy

Reputation: 444

Use setSelectionRange(beg, end) or selectionStart/selectionEnd to change the selection. Basically from current selection range, you try to get the index (start, end) of the span indices you're trying to select and then change the selection. Assuming you want to wrap/extend the selection to nearest "NEWLINE"s, here's a sample code:

var x = $("#input input:first")[0];
var value = x.value;
var NEWLINE = '\n'; // whatever is your newline delimiter.
var start = value.substr(0, x.selectionStart).lastIndexOf(NEWLINE);
if (start == -1) start = 0;
var end = value.substr(x.selectionEnd).indexOf(NEWLINE);
if (end == -1) end = value.length;

x.setSelectionRange(start, end); or x.selectionStart = start, x.selectionEnd = end;

Upvotes: 2

Related Questions