How to Determine the Middle of Cursor?

One of the most interesting aspects was that the tooltip appears in the middle of our cursor. How can we do that? Let's find out in this lesson.

What we have so far #

So far, we’ve investigated if we can use constant character widths to determine the middle, and we’ve tried to use the getSelection method alone to provide all the information we need.

We know that we’ll certainly have to use some information from getSelection, since it reliably gives us the selected characters. So the problem becomes this: given a string of characters in an HTML node, find the x and y offsets of the middle (so that we can have absolute position for the tooltip with top and left properties).

We can divide this into subproblems. If we can find the x and y offsets of any HTML element, one idea is to wrap the selected text in a span, get the x and y offsets and the width of that span, and consider the middle to be (x + width/2, y).

Googling “get x and y of html node,” I find the API getBoundingClientRect(), which has the properties we’re looking for. I’m not entirely sure how to determine if the selection spans multiple lines. Maybe we can use the height to determine that. We’ll see.

Let’s write some code to test if this method works.

I’m using console.log to print often, and continuously test if my intermediary steps work, like getting the selected text.

Get hands-on with 1200+ tech skills courses.