user2454455
user2454455

Reputation:

Why use removeAllRAnges() at the start of a selection?

I have this code working, i just want to understand why do i need to use removeAllRanges at the start. Did the sel had a ranges in it automatically when initialized?

function setCaret(boolean_position) {
   var range = document.createRange();
   var sel = window.getSelection();
   range.selectNodeContents($('#board_code')[0]);
   range.collapse(boolean_position);
   sel.removeAllRanges();
   sel.addRange(range);//setting the caret position
} 

Upvotes: 3

Views: 5257

Answers (1)

Reinmar
Reinmar

Reputation: 22023

Yes, the selection retrieved from window.getSelection() isn't an empty instance like the range created by document.createRange(). Notice the difference in these methods names - one creates new instance and second gets the instance.

The reason is simple - you can have multiple range instances, every containing different positions. But there's only one selection per document.

Therefore, before adding range, usually you have to remove old ranges that are currently selected. Unless, of course, that you want to extend current selection.

Update: As Tim correctly pointed out, only Firefox supports multiple selection ranges. This means that only on Firefox you're able to select more than one piece of DOM at a time - e.g. you can select table's column or add more selections using CTRL key.

Therefore, only Firefox requires that you execute removeAllRanges() before adding next ones. Other browsers will automatically remove old ranges.

Upvotes: 5

Related Questions