I have a long rectangular div (parent) with several smaller div (child) inside it. I want to click anywhere on the long rectangular div (including the child divs) to show the offset from the left of the parent div.
Currently this javascript code only works when I click outside the small divs, as soon as I click inside the child div, it shows me the offset of the child div. I'm quite new to javascript and can't seem to find relevant answers to this.
I hope someone could help, thanks in advance.
window.onload = function(){
parentDiv.addEventListener('click',function(e){
alert(e.offsetX);
}, false);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With