JavaScript mouse position when scrolled down the page.

When working on a project, I implemented a feature that required the x & y values of the mouse. Simple enough, however things didn’t work quite as expected when I would scroll down the page. If my mouse is at x = 100, y = 0, and I scroll down the page. The mouse values stay the same. But if I wanted to create a div or another element at the position of the mouse. Adding it to the document of the DOM appends it to 100,0 as if your screen is at the top. It doesn’t take into account the scroll offset.

Luckily there’s a simple fix for this:

Let’s say you have a link, and as an onclick event you want to show a div containing an un ordered list, and you wish to have it positioned at the mouse. Your HTML code would be something like:

<a href="#" id="clickMe">Show list</a>
<div id="list" style="display:none">
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
  </ul>
</div>

Utilizing our good friend jQuery, you add the click event

$(document).ready(function() {
  $('#clickMe').click(function(e) {
    var x = e.clientX;
    var y = e.clientY + document.body.scrollTop;
    $('#list').css({
      'display':'block',
      'position':'absolute',
      'z-index':'9999',
      'left':x+'px',
      'top':y+'px'
    });
  });
});

The code simply adds the click event, passing e as the parameter to be able to grab the mouse coordinates. The clientX and clientY properties return the mouse coordinates perspectively. The rest is done by applying CSS to the div.

The document.body.scrollTop is the key here. When you are scrolled to the top, it has a value of 0. For every pixel you scroll down, it increases. You can also use document.body.scrollLeft if you are concerned about side-scrolling offsets.