Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the position of a mouse click inside the parent div javascript

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);
like image 948
shshchch88 Avatar asked Mar 19 '14 02:03

shshchch88


1 Answers

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

like image 148
tewathia Avatar answered Nov 15 '22 01:11

tewathia