Search code examples
javascriptmobile-browser

Javascript for text highlight tooltip in mobile browsers


I want to open a tooltip beside text selected in a mobile browser (e.g., Chrome in Android). Since text selection in mobile browsers does not trigger mouse events, I cannot use mouseup event.

document.addEventListener("selectionchange", function(event) {

    var text = window.getSelection().toString();
    var tooltip = document.getElementById('tooltip');
    var x = event.clientX; // The problem
    var y = event.clientY; // The Problem
    tooltip.innerHTML = text;
    tooltip.style.top = x + 'px';
    tooltip.style.left = y + 'px';
});

The problem is that ClientX and ClientY do not work with selectionchange.

Check the JSFiddle.


Solution

  • You can get the bounding rect of the text selection and place the tooltip based on that data. The rect will tell you the width, height, x, y, top, right, bottom, and left of the selection.

    document.addEventListener("selectionchange", function(event) {
      const selection = window.getSelection();
      
      if (selection.rangeCount === 0) {
        return;
      }
    
      const range = selection.getRangeAt(0);
      const rect = range.getBoundingClientRect();
      const text = selection.toString();
      const tooltip = document.getElementById('tooltip');
    
      tooltip.innerHTML = text;
      tooltip.style.top = rect.bottom + 5 + 'px'; // 5px offset
      tooltip.style.left = rect.x + 5 + 'px';     // 5px offset
      tooltip.style.position = 'absolute';
      tooltip.style.background = 'lightgreen';
    });
    This is some text
    <div id="tooltip">