2

I'm trying to make use of this answer's tooltip code, but I've encountered a few problems. The tooltip doesn't let me type text in a <input> element and also makes jumps when I scroll far down the table, like this:

enter image description here

while it's supposed to follow the cursor. I made this fiddle: https://jsfiddle.net/nuvgef12/ and here's the code:

css:

.tooltip {
display: inline-block;
position: fixed;
padding: .5em 1em;
background-color: red;
}

html:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h4 id="log">pageX: -, pageY: -</h4>
<div class="tooltip">I'm a tooltip!</div>

<input type="text" placeholder="Enter something">
<table class='items'>
            <thead>
            <tr class="table-header">
                <th>Id</th>
                <th>Icon</th>
                <th>Name</th>
            </tr>
            </thead>

            <tr>
              <td>1</td>
              <td>1</td>
              <td>1</td>
            </tr>

            <tr>
              <td>12</td>
              <td>12</td>
              <td>12</td>
            </tr>
            ...

js:

$( document ).on( "mousemove", function( event ) {
  $( "#log" ).text( "pageX: " + event.pageX + ", pageY: " + event.pageY );
  $( ".tooltip" ).css({
    "left" : event.pageX,
    "top" : event.pageY
  });
});

EDIT:

The given solutions help with letting putting the text inside input, but there still exists the problem with jumping. It happens after a scroll down the table - the tooltip briefly disappears and then reappears much off to down and to the side.

parsecer
  • 4,758
  • 13
  • 71
  • 140

2 Answers2

1

If you add a little margin to your tooltip it will let your pointer click on the input instead of the tooltip

.tooltip {
  display: inline-block;
  position: fixed;
  margin: 1px;
  background-color: red;
}
Oded BD
  • 2,788
  • 27
  • 30
1

Add 1 to the X and Y position to allow you to select behind it, or add a margin-top:1px to your .tooltip will also work.

An easy fix to the scroll issue is to use clientX and clientY instead.

Here is the modified script:

$(window).on( "mousemove", function( event ) {
  $( "#log" ).text( "clientX: " + event.clientX + ", clientY: " + event.clientY );
  $( ".tooltip" ).css({
    "left" : event.clientX + 1,
    "top" : event.clientY + 1
  });  
});

Here is the working code.

You can read more here on the difference between them, but basically pageX is relative to the document's position within the viewport, which changes when scrolled, and clientX is relative to the viewport itself, which does not change in this way.

chris
  • 789
  • 4
  • 16