0

How can i catch the correct click position?

I have a self-made context-menu that I want to raise on the click position. The click is on a DOMelement in a jQueryUI.dialog() object. When i try, i gives me the wrong (for my use) coordinates.

Javascript:

$("a").on("contextmenu", function(eve){
  $("#contextmenu").show().css({
     left: eve.pageX,
     top: eve.pageY
  });
});


<div class="im-the-dialog">
    <div class="60% width">some content</div>
    <div>
        <ul>
            <li>
                <a class="clicked">click</a>
            </li>
        </ul>
    </div>
    <div class="the context menu">some links</div>
</div>

how can i fix it?

yossi
  • 3,090
  • 7
  • 45
  • 65
  • Related: http://stackoverflow.com/questions/6073505/what-is-the-difference-between-screenx-y-clientx-y-and-pagex-y – trysmudford Aug 17 '16 at 14:08

2 Answers2

1

this is how you get the right cordinates of click event

$(document).ready(function() {
  $('img').click(function(e) {
    var offset = $(this).offset();
    alert(e.pageX - offset.left); //x cordinate
    alert(e.pageY - offset.top);  //y cordinate
  });
});

Check this jsfiddle for your code

Edison Biba
  • 4,384
  • 3
  • 17
  • 33
0

You should be able to leverage the event properties without any calculations at all.

Assuming the dialog is absolutely positioned, the offsetX and offsetY properties should be all you need.

event.clientX and event.clientY are the coordinates you are looking for if your context menu is absolutely positioned within the body or statically positioned containers. More here . The clientX and clientY properties are supported at least as far back as ie8.

Community
  • 1
  • 1
cage rattler
  • 1,587
  • 10
  • 16
  • The problem is that the contextmenu is in the dialog (and can't go out).. so it must be positions relative to it. – yossi Aug 17 '16 at 14:51
  • then the offsetX and offsetY properties should be all you need. Amending the answer accordingly. – cage rattler Aug 17 '16 at 14:55