How to position a pop up element on mouse position coordinates with jquery

Here is a simple yet useful trick to position a tooltip (a div element etc) near the mouse click or pointer position using jQuery. In the example here, we have a tool tip (div) with id “tooltip”, a href tag, on clicking which the pop up is positioned and a snippet of code to place anywhere on the page. Obviousaly this small function can be used to return mouse event coordinates by makeing slightest changes.

I have not tested this code jquery version prior to 1.3.2.

So, here is the javascript code:

$(document).ready(function()  {
  $("#tooltip_link").click(function(e){
    var x = e.pageX;
    var y = e.pageY;
    alert(x +', '+ y);
    $("#tooltip").css({"top":y, "left":x, "position":"absolute"});
    $(this).unbind('click');
  });
}

The code line below is used to stop click event when action is already over:

$(this).unbind('click');

And href and div tag html code:

CLICK




Once there was a man who lived in a forest. He ate in the forest and slept in the forest. He was very happy living in the forest. At last he died in the forest. No one knows why the man lived in the forest. I know this is not a happy story. The end!

3 thoughts on “How to position a pop up element on mouse position coordinates with jquery

  1. What intrigues me is the popups on this site, not the code snippet.
    What I am looking for is exactly what happens when you hover over the blue words on this page with the dotted underline: a pop-up that you can move into and with dynamic clickable text.
    When I look at the source code of this page I don’t see any mark-up for these “blue-linked” words. How are they made into links. What is the code for the ad popups??
    Do you want to share that with us. That would really be great.
    Yonathan

Leave a Reply