Stranger
Stranger

Reputation: 27

JavaScript: How to find out the position of the mouse in the div box?

I know how to find out the position of the mouse relative to the top-left corner of the browser window, but I don't know how to do so relative to the top-left corner of the div box.

Upvotes: 0

Views: 275

Answers (3)

user160820
user160820

Reputation: 15230

Try the follow Javascript function.

var IE = document.all?true:false

if (!IE) {
 document.captureEvents(Event.MOUSEMOVE);
}



function getMousePosition(e) {
  if (IE) { 
    var X = event.clientX + document.body.scrollLeft
    var Y = event.clientY + document.body.scrollTop
  } else { 
    var X = e.pageX
    var Y = e.pageY
  }  

  if (X < 0) {
       X = 0
   }
  if (Y < 0) {
     Y = 0
  }  
  alert("X : "+ X +" Y: "+ Y);
}

document.onmousemove = getMousePosition;

Upvotes: 1

NawaMan
NawaMan

Reputation: 25687

According to this page, there are 6 pairs of coordinate. You may try them. I guess the right one might be clientX,clientY.

Hope this helps.

Upvotes: 0

Christopher Stott
Christopher Stott

Reputation: 1478

If you get the top-left corner of the div box, you can just subtract this from the screen coordinates of the mouse.

Upvotes: 0

Related Questions