Skip to content

Commit ed25d47

Browse files
committed
minor
1 parent 8319c71 commit ed25d47

File tree

1 file changed

+111
-48
lines changed

1 file changed

+111
-48
lines changed

2-ui/99-ui-misc/02-selection-range/article.md

Lines changed: 111 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -6,25 +6,27 @@ libs:
66

77
# Selection and Range
88

9-
In this chapter we'll cover text selection.
9+
In this chapter we'll cover selection in the document, as well as selection in form fields, such as `<input>`.
1010

11-
JavaScript can do everything with it: get the existing selection, select/deselect it or its parts, remove the selected part from the document, wrap it into a tag, and so on.
11+
JavaScript can do get the existing selection, select/deselect both as a whole or partially, remove the selected part from the document, wrap it into a tag, and so on.
1212

13-
You can get a few ready to use recipes at the end, in "Summary" section. But you'll get much more if you read on. The underlying `Range` and `Selection` objects are easy to grasp, and then you'll need no recipes to make them do what you want.
13+
You can get ready to use recipes at the end, in "Summary" section. But you'll get much more if you read the whole chapter. The underlying `Range` and `Selection` objects are easy to grasp, and then you'll need no recipes to make them do what you want.
1414

1515
## Range
1616

1717
The basic concept of selection is [Range](https://dom.spec.whatwg.org/#ranges): basically, a pair of "boundary points": range start and range end.
1818

19-
Each point represented as a parent DOM node with the relative offset from its start. For an element node, the offset is a child number, for a text node it's the position in the text.
19+
Each point represented as a parent DOM node with the relative offset from its start. If the parent node is an element element node, then the offset is a child number, for a text node it's the position in the text. Examples to follow.
20+
21+
Let's select something.
2022

2123
First, we can create a range (the constructor has no parameters):
2224

2325
```js
2426
let range = new Range();
2527
```
2628

27-
Then we can set the boundaries using `range.setStart(node, offset)` and `range.setEnd(node, offset)`.
29+
Then we can set the selection boundaries using `range.setStart(node, offset)` and `range.setEnd(node, offset)`.
2830

2931
For example, consider this fragment of HTML:
3032

@@ -123,7 +125,7 @@ E.g. selecting from `1` to `4` gives range `<i>italic</i> and <b>bold</b>`.
123125

124126
![](range-example-p-1-3.png)
125127

126-
We don't have to use the same node in `setStart` and `setEnd`. A range may span across many unrelated nodes.
128+
We don't have to use the same node in `setStart` and `setEnd`. A range may span across many unrelated nodes. It's only important that the end is after the start.
127129

128130
### Selecting parts of text nodes
129131

@@ -135,7 +137,7 @@ That's also possible, we just need to set the start and the end as a relative of
135137

136138
We need to create a range, that:
137139
- starts from position 2 in `<p>` first child (taking all but two first letters of "Ex<b>ample:</b> ")
138-
- ends at the position 3 in `<b>` first child (taking first three letters of "<b>bol</b>d"):
140+
- ends at the position 3 in `<b>` first child (taking first three letters of "<b>bol</b>d", but no more):
139141

140142
```html run
141143
<p id="p">Example: <i>italic</i> and <b>bold</b></p>
@@ -272,7 +274,7 @@ Here's a screenshot of a selection with 3 ranges, made in Firefox:
272274

273275
![](selection-firefox.png)
274276

275-
Other browsers support at maximum 1 range per selection. As we'll see, some of `Selection` methods imply that there may be many ranges, but again, in all browsers except Firefox, there's at maximum 1.
277+
Other browsers support at maximum 1 range. As we'll see, some of `Selection` methods imply that there may be many ranges, but again, in all browsers except Firefox, there's at maximum 1.
276278

277279
## Selection properties
278280

@@ -309,13 +311,12 @@ That's different from `Range` objects that are always directed forward: the rang
309311

310312
There are events on to keep track of selection:
311313

312-
- `elem.onselectstart` -- when a selection starts.
313-
- May trigger on any element.
314-
- Preventing default action makes the selection not start.
315-
- `document.onselectionchange` -- when a selection changes.
316-
- Triggers only on `document`.
314+
- `elem.onselectstart` -- when a selection starts on `elem`, e.g. the user starts moving mouse with pressed button.
315+
- Preventing the default action makes the selection not start.
316+
- `document.onselectionchange` -- whenever a selection changes.
317+
- Please note: this handler can be set only on `document`.
317318

318-
## Selection tracking demo
319+
### Selection tracking demo
319320

320321
Here's a small demo that shows selection boundaries
321322
dynamically as it changes:
@@ -334,6 +335,8 @@ From <input id="from" disabled> – To <input id="to" disabled>
334335
</script>
335336
```
336337

338+
### Selection getting demo
339+
337340
To get the whole selection:
338341
- As text: just call `document.getSelection().toString()`.
339342
- As DOM nodes: get the underlying ranges and call their `cloneContents()` method (only first range if we don't support Firefox multiselection).
@@ -374,21 +377,21 @@ Selection methods to add/remove ranges:
374377
- `removeAllRanges()` -- remove all ranges.
375378
- `empty()` -- alias to `removeAllRanges`.
376379

377-
Also, there are methods to manipulate the selection range directly:
380+
Also, there are convenience methods to manipulate the selection range directly, without `Range`:
378381

379382
- `collapse(node, offset)` -- replace selected range with a new one that starts and ends at the given `node`, at position `offset`.
380383
- `setPosition(node, offset)` -- alias to `collapse`.
381384
- `collapseToStart()` - collapse (replace with an empty range) to selection start,
382385
- `collapseToEnd()` - collapse to selection end,
383386
- `extend(node, offset)` - move focus of the selection to the given `node`, position `offset`,
384-
- `setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset)` - replace selection range with the given anchor and focus. All content in-between them is selected.
387+
- `setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset)` - replace selection range with the given start `anchorNode/anchorOffset` and end `focusNode/focusOffset`. All content in-between them is selected.
385388
- `selectAllChildren(node)` -- select all children of the `node`.
386389
- `deleteFromDocument()` -- remove selected content from the document.
387390
- `containsNode(node, allowPartialContainment = false)` -- checks whether the selection contains `node` (partically if the second argument is `true`)
388391

389392
So, for many tasks we can call `Selection` methods, no need to access the underlying `Range` object.
390393

391-
For example, selecting the whole contents of the paragraph:
394+
For example, selecting the whole contents of the paragraph `<p>`:
392395

393396
```html run
394397
<p id="p">Select me: <i>italic</i> and <b>bold</b></p>
@@ -421,31 +424,41 @@ The exception is some selection methods, that replace the existing selection, li
421424

422425
## Selection in form controls
423426

424-
Form elements, such as `input` and `textarea` provide [API for selection in their values](https://html.spec.whatwg.org/#textFieldSelection).
425-
426-
As the value is a pure text, not HTML, these methods to not use `Selection` or `Range` objects, they are much simpler.
427+
Form elements, such as `input` and `textarea` provide [special API for selection](https://html.spec.whatwg.org/#textFieldSelection), without `Selection` or `Range` objects. As an input value is a pure text, not HTML, there's no need for such objects, everything's much simpler.
427428

428-
- `input.select()` -- selects everything in the text control,
429+
Properties:
429430
- `input.selectionStart` -- position of selection start (writeable),
430431
- `input.selectionEnd` -- position of selection start (writeable),
431-
- `input.selectionDirection` -- direction, one of: "forward", "backward" or "none" (if e.g. selected with a double mouse click),
432-
- `input.setSelectionRange(start, end, [direction])` -- change the selection to span from `start` till `end`, in the given direction (optional).
432+
- `input.selectionDirection` -- selection direction, one of: "forward", "backward" or "none" (if e.g. selected with a double mouse click),
433+
434+
Events:
435+
- `input.onselect` -- triggers when something is selected.
436+
437+
Methods:
438+
439+
- `input.select()` -- selects everything in the text control (can be `textarea` instead of `input`),
440+
- `input.setSelectionRange(start, end, [direction])` -- change the selection to span from position `start` till `end`, in the given direction (optional).
441+
- `input.setRangeText(replacement, [start], [end], [selectionMode])` -- replace a range of text with the new text.
433442

434-
To modify the content of the selection:
443+
Optional arguments `start` and `end`, if provided, set the range start and end, otherwise user selection is used.
435444

436-
- `input.setRangeText(replacement, [start], [end], [selectionMode])` -- replace a range of text with the new text. If the `start` and `end` arguments are not provided, the range is assumed to be the selection.
445+
The last argument, `selectionMode`, determines how the selection will be set after the text has been replaced. The possible values are:
437446

438-
The last argument, `selectionMode`, determines how the selection will be set after the text has been replaced. The possible values are:
447+
- `"select"` -- the newly inserted text will be selected.
448+
- `"start"` -- the selection range collapses just before the inserted text.
449+
- `"end"` -- the selection range collapses just after the inserted text.
450+
- `"preserve"` -- attempts to preserve the selection. This is the default.
439451

440-
- `"select"` -- the newly inserted text will be selected.
441-
- `"start"` -- the selection range collapses just before the inserted text.
442-
- `"end"` -- the selection range collapses just after the inserted text.
443-
- `"preserve"` -- attempts to preserve the selection. This is the default.
452+
Now let's see these methods in action.
453+
454+
### Example: tracking selection
444455

445456
For example, this code uses `onselect` event to track selection:
446457

447-
```html run
448-
<textarea id="area" style="width:80%;height:60px">Select this text</textarea>
458+
```html run autorun
459+
<textarea id="area" style="width:80%;height:60px">
460+
Selecting in this text updates values below.
461+
</textarea>
449462
<br>
450463
From <input id="from" disabled> – To <input id="to" disabled>
451464

@@ -457,23 +470,29 @@ From <input id="from" disabled> – To <input id="to" disabled>
457470
</script>
458471
```
459472

460-
The `document.onselectionchange` event should not trigger for selections inside a form control, according to the [spec](https://w3c.github.io/selection-api/#dfn-selectionchange), as it's not related to `document` selection and ranges. Some browsers generate it though.
473+
Please note:
474+
- `onselect` triggers when something is selected, but not when the selection is removed.
475+
- `document.onselectionchange` event should not trigger for selections inside a form control, according to the [spec](https://w3c.github.io/selection-api/#dfn-selectionchange), as it's not related to `document` selection and ranges. Some browsers generate it, but we shouldn't rely on it.
461476

462-
**When nothing is selected, `selectionStart` and `selectionEnd` both equal the cursor position.**
463477

464-
Or, to rephrase, when nothing is selected, the selection is collapsed at cursor position.
478+
### Example: moving cursor
465479

466-
We can use it to move cursor:
480+
We can change `selectionStart` and `selectionEnd`, that sets the selection.
467481

468-
```html run
482+
An important edge case is when `selectionStart` and `selectionEnd` equal each other. Then it's exactly the cursor position. Or, to rephrase, when nothing is selected, the selection is collapsed at the cursor position.
483+
484+
So, by setting `selectionStart` and `selectionEnd` to the same value, we move the cursor.
485+
486+
For example:
487+
488+
```html run autorun
469489
<textarea id="area" style="width:80%;height:60px">
470490
Focus on me, the cursor will be at position 10.
471491
</textarea>
472492

473493
<script>
474494
area.onfocus = () => {
475-
// zero delay setTimeout is needed
476-
// to trigger after browser focus action
495+
// zero delay setTimeout to run after browser "focus" action finishes
477496
setTimeout(() => {
478497
// we can set any selection
479498
// if start=end, the cursor it exactly at that place
@@ -483,23 +502,67 @@ Focus on me, the cursor will be at position 10.
483502
</script>
484503
```
485504

486-
...Or to insert something "at the cursor" using `setRangeText`.
505+
### Example: modifying selection
487506

488-
Here's an button that replaces the selection with `"TEXT"` and puts the cursor immediately after it. If the selection is empty, the text is just inserted at the cursor position:
507+
To modify the content of the selection, we can use `input.setRangeText`. Of course, we can read `selectionStart/End` and can just change `value`, but `setRangeText` is more powerful.
489508

490-
```html run
491-
<textarea id="area" style="width:80%;height:60px">Select something here</textarea>
492-
<br>
509+
That's a somewhat complex method. In its simplest one-argument form it replaces the user selected range and removes the selection.
510+
511+
For example, here the user selection will be wrapped by `*...*`:
512+
513+
```html run autorun
514+
<input id="input" style="width:200px" value="Select here and click the button">
515+
<button id="button">Wrap selection in stars *...*</button>
493516

494-
<button id="button">Insert!</button>
517+
<script>
518+
button.onclick = () => {
519+
if (input.selectionStart == input.selectionEnd) {
520+
return; // nothing is selected
521+
}
522+
523+
let selected = input.value.slice(input.selectionStart, input.selectionEnd);
524+
input.setRangeText(`*${selected}*`);
525+
};
526+
</script>
527+
```
528+
529+
With more arguments, we can set range `start` and `end`.
530+
531+
In this example we find `"THIS"` in the input text, replace it and keep the replacement selected:
532+
533+
```html run autorun
534+
<input id="input" style="width:200px" value="Replace THIS in text">
535+
<button id="button">Replace THIS</button>
536+
537+
<script>
538+
button.onclick = () => {
539+
let pos = input.value.indexOf("THIS");
540+
if (pos >= 0) {
541+
input.setRangeText("*THIS*", pos, pos + 4, "select");
542+
input.focus(); // focus to make selection visible
543+
}
544+
};
545+
</script>
546+
```
547+
548+
### Example: insert at cursor
549+
550+
If nothing is selected, or we use equal `start` and `end` in `setRangeText`, then the new text is just inserted, nothing is removed.
551+
552+
We can also insert something "at the cursor" using `setRangeText`.
553+
554+
Here's an button that inserts `"HELLO"` at the cursor position and puts the cursor immediately after it. If the selection is not empty, then it gets replaced (we can do detect in by comparing `selectionStart=selectionEnd` and do something else instead):
555+
556+
```html run autorun
557+
<input id="input" style="width:200px" value="Text Text Text Text Text">
558+
<button id="button">Insert "HELLO" at cursor</button>
495559

496560
<script>
497561
button.onclick = () => {
498-
// replace range with TEXT and collapse the selection at its end
499-
area.setRangeText("TEXT", area.selectionStart, area.selectionEnd, "end");
562+
input.setRangeText("HELLO", input.selectionStart, input.selectionEnd, "end");
563+
input.focus();
500564
};
501565
</script>
502-
</body>
503566
```
504567

505568

0 commit comments

Comments
 (0)