Michael Wood
Michael Wood

Reputation: 101

Using jQuery to align an element to mouse location has an offset

I'm working on a mapping feature and the jQuery script that aligns the element to the mouse location has an offset that seems to match the page spacing.

Here is the testing area http://champagnecentre.com/dev/directory/

jQuery(document).mousemove(function(e){
   jQuery('.directory-listing').css({top:e.pageY,left:e.pageX});
});

Upvotes: 0

Views: 59

Answers (2)

Dominic Aquilina
Dominic Aquilina

Reputation: 617

EDIT: As per @Bwolfing's comment below, my interpretation of the spec was incorrect. I have updated the plunk below to propose an alternate solution to that proposed above. Changing the position of the tooltip to fixed forces it to be relative to the page.

https://plnkr.co/8CCns5mwdqSoWiGK1SDN

HTML

<!DOCTYPE html>
<html>

  <head>
    <script data-require="[email protected]" data-semver="2.2.4" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div class="offsetWrapper">
      <h1 id="myH1">Hello Plunker!</h1>
    </div>
  </body>

</html>

JS

$(document).on ('mousemove', function (event)
{
  $('#myH1').css ({'left', event.pageX, 'top', event.pageY});
});

CSS

#myH1 {
  position: fixed;

  margin: 0;
}

.offsetWrapper {
  position: relative;
  left: 100px;
  top: 100px;

  /*Show the position of the container for reference*/
  background-color: red;
  height: 10px;
  width: 10px;
}

Upvotes: 0

Sam0
Sam0

Reputation: 1459

@Bwolfing is right I believe. e.pageY and e.pageX relate to the document. As your div is nested the top and left positions are relative to the parent, which is leading to the offset.

by using .parent().offset() we can workout the offsets, fiddle below. I've added .area as a displaced div in which to nest .directory-listing, the .mousemove function can be attributed to $(document)... or $('.area')..., note that .mousemove is better written a subject of .on:

$(document).on({
  mouseenter: function(e) {
    // special effects
  },
  mousemove: function(e) {
    e.preventDefault();
    var target = $('.directory-listing'),
      d = target.parent().offset(), // this gets the offset positions
      dX = d.left + 6,
      dY = d.top + 12; // the +6 and +12 here are just to center the 'x'
    target.css({
      left: e.pageX - dX,
      top: e.pageY - dY
    });
  },
  mouseleave: function(e) {
    // special effects
  },
  click: function(e) {
    // special effects
  }
});
.area {
  position: absolute;
  left: 10%;
  top: 100px;
  width: 40%;
  height: 50%;
  background: #bbb;
  border: 1px solid #09f;
}
.directory-listing {
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<div class="area">
  <div class="directory-listing">X</div>
</div>

Upvotes: 1

Related Questions