0

I am trying to get the position of the click when the user click whatever part of the window. I found this code in many tutorials but it seems not to work.

(function( $ ) {
    $( document ).ready(function() {

        $( window ).click(function( e ) {
            var offset = $(this).offset(),
                relativeX = (e.pageX - offset.left),
                relativeY = (e.pageY - offset.top);

                alert("X: " + relativeX + "  Y: " + relativeY);
        });
    });
})( jQuery );

Firefox console tells me "TypeError: offset is undefined" and I don't understand why it does not work.

Which is the right way to retrieve the click position on the window?

ctrlmaniac
  • 404
  • 4
  • 13
  • 28

4 Answers4

6

That code is really close to working. It will work correctly if you replace $(this) with $(e.target). This will get the left and top offsets of the click event, not the window itself.

(function($) {
    $(document).ready(function() {

        $(window).click(function(e) {
            var relativeX = (e.pageX - $(e.target).offset().left),
                relativeY = (e.pageY - $(e.target).offset().top);

                alert("X: " + relativeX + "  Y: " + relativeY);
        });
    });
})(jQuery);

http://jsfiddle.net/IronFlare/7wsamt87/

IronFlare
  • 2,287
  • 2
  • 17
  • 27
2

If you're clicking on the window like that, you don't really need an offset.

$(window).click(function (e) {

        alert("X: " + e.pageX + "  Y: " + e.pageY);
    });
enigma
  • 3,476
  • 2
  • 17
  • 30
1

Your code is assuming the wrong this;

In your listener, this will be window, but $(window).offset(); makes no sense, which is why the method returns null or undefined.

Perhaps you meant to use document.documentElement, document.body or e.target which would be the <html>, <body> or the clicked node, respectively.

$(document.body).offset();
Paul S.
  • 64,864
  • 9
  • 122
  • 138
0
I hope to have find a solution

function showCoords(event) {
    var x = event.clientX;
    var y = event.clientY;
    var coords = "X coords: " + x + ", Y coords: " + y;
    document.getElementById("demo").innerHTML = coords;
}
<!DOCTYPE html>
<html>
<body>

<h2 onclick="showCoords(event)">Click this heading to get the x (horizontal) and y (vertical) coordinates of the mouse pointer when it was clicked.</h2>

<p><strong>Tip:</strong> Try to click different places in the heading.</p>

<p id="demo"></p>



</body>
</html>
Riccardo
  • 66
  • 2
  • 16
  • 1
    This question is about the _click_ event, not _mousemove_. Also, how far back is this attempting to support? IE5? – Paul S. Apr 23 '15 at 00:25
  • 1
    Attribution: http://stackoverflow.com/questions/7790725/javascript-track-mouse-position#answer-7790764 – Stryner Apr 23 '15 at 00:27
  • Stryner I have soon removed my comment, there is no need to keep this comment – Riccardo Apr 23 '15 at 00:35