How to get the coordinates of the mouse inside a relatively positioned element?

I want to position an element $menu on the mouse's pointer (on click). $menu is inside $icon which has position: relative. ($menu has position absolute.)

$(document).ready(function() {
  $("a").click(function(ev) {
    var $icon = $(ev.currentTarget)
    var $menu = $icon.next()
    var thisPos = $icon.position()
    var x = ev.clientX
    var y = ev.clientY
    $menu.css('top', y + 'px')
    $menu.css('left', x + 'px')
  });
})
nav > ul[_v-2e9e2f12] {
  background: #3a3c3a;
  margin: 0;
  padding: 10px;
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  z-index: 9999;
  box-shadow: 2px 0 1px rgba(0, 0, 0, 0.1);
}

nav > ul li[_v-2e9e2f12] {
  display: block;
  margin: 0 0 8px;
  text-align: center;
  position: relative;
  -webkit-transition: all 0.2s ease-in-out;
  transition: all 0.2s ease-in-out;
  width: 48px;
  height: 48px;
  background: #ccc;
}

ul[_v-0078ee36] {
  background: #3a3c3a;
  position: absolute;
  border-radius: 3px;
  box-shadow: 0 2px 1px rgba(0, 0, 0, 0.1);
}

a[_v-2e9e2f12] {
  display: block;
  width: 48px;
  height: 48px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
  <ul _v-2e9e2f12="">
    <li _v-2e9e2f12="">
      <a _v-2e9e2f12="">
      </a>
      <ul _v-0078ee36="" _v-2e9e2f12="">
        Hello!
      </ul>
    </li>
    <li _v-2e9e2f12="">
      <a _v-2e9e2f12="">
      </a>
      <ul _v-0078ee36="" _v-2e9e2f12="">
        Hello!
      </ul>
    </li>
  </ul>
</nav>

But I get a weird behavior: $menu is not positioned on the mouse's pointer but a few pixels to the right and bottom. And for the second element it's even worse: many pixels to the right and bottom.

How to fix this, and make $menu to be positioned right in the mouse's pointer?

Here's the JSFiddle.

Answers 1

Related Articles