WebDevGuy2 WebDevGuy2 - 8 months ago 29
Javascript Question

How to click and have x/y position written at that position?

I have an image on a page. I want to be able to click all over the image and at the point of click output the x/y position (coordinates), for each click. How can I do that?

NOTE: I already know how to get the x/y coordinate. My question centers around how do I write the x/y coordinates to the screen at those exact coordinates?

I suppose on the click even of the image I would dynamically write an inline div with the text coordinates in it. But I have no idea how to implement that. Thanks!


Here is a working snippet. Idea is to bind a click event to the img element and on click create a dynamic span tag and set its top and left css property to event.offsetY and event.offsetX respectively. This will make sure the span is places exactly where the click happened.

  var span = "<span style='position:absolute;top:"+e.offsetY+"px;left:"+e.offsetX+"px'>"+e.offsetX +","+ e.offsetY+"</span>"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRGXr0yFkbJ07wEoT9Eg1nO2nA2Vsr8g5wXKRk4BkUPudku-BwC8Q" alt="my image">