Search code examples
javascripttooltipmouseevent

Check which side has more space around mouse pointer


I am building a custom tooltip functionality where I am supposed to show a video as a tooltipo over an image. Now, I have some initial thing working, but I am stuck at finding the area around mouse pointer where I should display the tooltip.

I am having the tooltip always visible at the bottom right of mouse cursor, no matter where mouse currently is in screen, this is what I have so far :

window.onmousemove = function (e) {
    var x = e.clientX, y = e.clientY;
    tooltipSpan.style.top = (y + 10) + 'px';
    tooltipSpan.style.left = (x + 10) + 'px';
};

where tooltip is my target element. What I am looking for, is, that my code should find the largest area around mouse available on screen, and adjust the tooltip to display there. Any pointers for this would help a lot.

Note: jQuery is not an option, I have to build in core JS.


Solution

    1. You can get the width and the dimensions of the viewport using window.innerWidth and window.innerHeight (in my example below this refers to window because the code is running inside window)
    2. Using viewport dimensions and the mouse position using ev.clientX/Y you can determine the pixel space on the left/right and top/bottom side of the cursor as in example below.

    3. Using property offsetWidth and offsetHeight we get the dimensions of the tooltip and we can use that to set the tooltip position relative to cursor position. For example if the topLeft quadrant is the largest, the tooltip will show top left relatively to cursor (meaning the bottom right corner of the tooltip will "touch" the cursor).

    I hope this example helps :).

     var tooltip = this.document.getElementsByClassName("tooltip")[0];
    window.onmousemove = function(ev) {
      // Getting pixel space 
      var leftPixelSpace = ev.clientX;
      var rightPixelSpace = this.innerWidth - leftPixelSpace; 
      var topPixelSpace = ev.clientY;
      var bottomPixelSpace = this.innerHeight - topPixelSpace;
    
      // Determining the position of topleft corner of the tooltip
      var tooltipPosX = leftPixelSpace > rightPixelSpace ? leftPixelSpace  - tooltip.offsetWidth : leftPixelSpace;
      var tooltipPosY = topPixelSpace > bottomPixelSpace ? topPixelSpace - tooltip.offsetHeight : topPixelSpace;
      
      // Setting tooltip position 
      tooltip.style.left = tooltipPosX+"px";
      tooltip.style.top = tooltipPosY+"px";
    };
    .tooltip {
      width: 150px;
      height: 100px;
      border: 1px solid black;
      background-color : lightblue;
      text-align: center;
      position: absolute
    }
    <div class="tooltip">floating tooltip</div>