Getting the position of a mouse click inside the parent div javascript
You can use the getClientRects
method with the clientX
event value to get the net offset coordinate:
var offset = this.getClientRects()[0];
alert(e.clientX - offset.left);
DEMO
First, I recommend learning a bit about DOM event bubbling and capturing. This is a DOM thing, not so much a Javascript thing, but essential to know. Rather than repeat it here, read this answer.
So, when you click on the child div
, the event is first presented to the element that fired the event, which is the child div
. It, however, does not have an event handler so the event bubbles up to the parent div
. It does have a handler, which is invoked with the event object passed as arg e
. Different browsers have different implementations of the event object. Since you're using offsetX
you're probably using IE (or Opera) and not Chrome, Safari, or Firefox. According to this doc from Microsoft, offsetX()
"sets or retrieves the x-coordinate of a pointer's position relative to the object firing the event". So, even though it's the parent div
's event handler running, you'll get the position relative to the child since it was the object firing the event.
Since you are new to JavaScript, I'll add this: due to the many incompatibilities between browsers, it is STRONGLY recommend that you use a JavaScript library that will handle these giving you a single normalized API. Your life will be easier, you'll be able to do much more, and your code will work on more than just IE. jQuery is a very popular one (and is in itself very beautiful). Read about jQuery's normalized Event Object.