3

I want to detect where in the div with id clickdetectiondiv have i clicked. The code that I am using gives me the position with respect to the top left of the body of the HTML page. I have spent lot of time in figuring out how this could be done but am unable to find the answer. One solution i have is to subtract the position of this absolutely positioned div. But not always will I get the position of the div, as the screen sizes may vary. Please tell me an alternate method to do this.

Thanks in advance,

<html>
<head>
<script type="text/javascript"> 
function clicked(event){
    var x=event.clientX
    var y=event.clientY
    document.getElementById("outputdiv").innerHTML= "X coords: " + x + ", Y coords: " + y;
}
</script>

<style type="text/css">
#clickdetectiondiv{
    position: absolute;
    top: 100px;
    left: 100px;
    height: 100px;
    width: 500px;
    background: gray;
}
#outputdiv{
    position: absolute;
    top: 300px;
    left: 100px;
    height: 100px;
    width: 500px;
    background: #eee;
    text-align: center;
}
</style>

</head>

<body>
<div id="clickdetectiondiv" onmousedown="clicked(event);"></div>
<div id="outputdiv"></div>
</body>

</html>
  • Try http://stackoverflow.com/questions/442404/dynamically-retrieve-the-position-x-y-of-an-html-element to figure the position of the div, and subrtact from that? – mariusnn Oct 12 '12 at 10:42
  • Here is about canvas. I think div has similiar solution: http://stackoverflow.com/questions/3234256/find-mouse-position-relative-to-element – karaxuna Oct 12 '12 at 10:43

3 Answers3

0

You want to use a javascript framework like jquery or mootools, they have functions to get relative position of an element to any other element you want already written in a cross-browser manner. Why reinvent the wheel?

xception
  • 4,241
  • 1
  • 17
  • 27
0

If you can use jquery

$('#A').click(function(e) {   //Default mouse Position 
              alert(e.pageX+ ' , ' + e.pageY);
       });
Buzz
  • 6,030
  • 4
  • 33
  • 47
0

I suppose this can be solution:

function clicked(event){
    var x = event.x;
    var y = event.y;

    var divClicked = document.getElementById("clickdetectiondiv");

    x -= divClicked.offsetLeft;
    y -= divClicked.offsetTop;
    document.getElementById("outputdiv").innerHTML= "X coords: " + x + ", Y coords: " + y;
}
maxwell
  • 857
  • 8
  • 16