Basic question, what is purpose of anchor and head?


Sorry to ask a really basic question. The Selection class has $anchor and $head properties. I think anchor can be before or after head, depending on which direction the user selects text (similar to the DOM Selection API’s anchor and focus I think). In what scenarios would you care about the direction of the text selection? I’ve wracked my head on it and can’t figure it out. I asked on StackOverflow a day ago, and just got downvoted with no answer. I’ve spent some hours trying to find an answer on Google and have come up with nothing. I think it must just be a blatantly obvious answer that I’m not seeing. Would someone be so kind to at least point me in the right direction?


One reason I can think of is if you wanted to display a tooltip at the location closest to the user’s mouse after a selection. For this, you would use the selection $head.


That’s exactly their purpose. They encode information about the direction of the selection, which also makes it possible (on modern browsers) to set the DOM selection correctly, so that further shift-arrow or shift-click changes move the correct side of the selection.


Thank you @marijn and @supersonicecho.