Skip to content Skip to sidebar Skip to footer

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 l

Solution 1:

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


Solution 2:

Try this way:

JS

$(document).ready(function () {
    $(document).on("mouseup", ".conttext", function () {
        var highlight = window.getSelection();
        console.log(highlight);
        var spn = '<span class="highlight">' + highlight + '</span>';
        var text = $('.conttext').text();
        $('.conttext').html(text.replace(highlight, spn));
    });
    $(document).on("mouseover", ".highlight", function () {
        alert("You hovered on selected tex"); // Your tooltip code goes here
    })
});

CSS:

.highlight {
    color:#888;
    position:relative;/*This will not matter if you inject tooltip using JS*/
    display:inline-block;/*This will not matter if you inject tooltip using JS*/
}

HTML:

<div class="conttext">Sample text</div>

Demo: http://jsfiddle.net/lotusgodkk/BGKSN/202/


Post a Comment for "Detect Hover On Selected Text"