I am building a WYSIWYG rich text editor.
When the user selects a portion of his/her text, I would like to present a menu in a tooltip. Presenting the menu works fine but I would like to only show it if the user hovers over the selected text.
As Illustrated:
I also haven't decided on positioning (I like the way that it's illustrated) but to clarify, that's not the point of the question.
The question is: How do I filter for a hover event that happens over selected text?
The Problems:
I can't just listen for a text selection event or test hover events to see whether they are over elements that have selected text inside them. The left image would generate a false positive with that.
I know how to get the selected text but I don't know how to get the selected region.
To my mind, the ideal solution is somehow to calculate the region of the selected text and test whether mouseover events happen in that region.
On mouseup
, use Range.getClientRects to grab the bounding rectangles of each line of the selection.
You can then test if the mouse is over the selection like this:
var cr= [];
$(document).on({
'mouseup': function() {
cr= window.getSelection().getRangeAt(0).getClientRects();
},
'mousemove': function(ev) {
//hide the pop up
for(var i = 0 ; i < cr.length ; i++) {
if(ev.pageX >= cr[i].left && ev.pageX <= cr[i].right &&
ev.pageY >= cr[i].top && ev.pageY <= cr[i].bottom
) {
//show the pop up
break;
}
}
}
});
Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With