Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect hover on selected text

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:

enter image description here

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:

  1. 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.

  2. 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.

like image 591
jcuenod Avatar asked Jun 02 '15 14:06

jcuenod


1 Answers

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

like image 183
Rick Hitchcock Avatar answered Sep 30 '22 14:09

Rick Hitchcock