Cursors and selections, how do they work in modern Browsers?


If you came across this blog post you’ll probably want to play around with cursor positions or text selections. Maybe add a new one, or just mark text highlighted after you selected text, the options are infinite (not really).

All browsers support this (even IE9+!), so don’t you be worried about this manipulation not working in your project.

Range vs Selection

he cursor position is that small vertical bar that appears in your text editor when you are writing (and what I’m seeing as I’m writing this), but for the browser, it’s a Selection, everything is a Selection even the single caret blinking in your screen.

The Selection in the browser is split into two types, caret, and range. Also, this selection will be a set of Ranges (maximum of 1 for all browsers except Firefox). The caret type represents a single marker in the screen, where the range object will have the same target (start and end). Finally, the range type represents a range where the start container will be different than the end container.

To get this Selection you can use window or document object in javascript (or if you are using other third parties libraries you’ll probably have a similar object).


This will return a Selection object where you’ll have a set of information, including the type of the selection, range count and the corresponding range objects.

For an example, imagine that you are editing a text (in some HTML element) and you want to know which is the caret or the selection position in the current text element.

const selectionStart = target.selectionStart;
const selectionEnd = target.selectionEnd;
// create range for the current selection
const range = new Range();

Now, you want know the exact screen position of this new Range. For this we have to set the start and end position of the selection.

range.setStart(target, target.selectionStart);
range.setEnd(target, target.selectionEnd);

By creating a range object, you can access the exact screen position of the selection in the target element. After this you can do all sort of tricks in your page.


Bonus section

hat about page selections? Imagine that you open a page and you select a bunch of different HTML elements. You want to know exactly when you start the selection and when you end it. Having in mind the previous selection object that we retrieved we can check that the type now is a range, which implies that our range object will have an array of different screen positions that we can access by using Range.getClientRects().