Getting mouse click position inside parent javascript div

I have a long rectangular div (parent) with a few smaller divs (children) inside it. I want to click anywhere on a long rectangular div (including child divs) to show the offset to 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 am completely new to javascript and cannot find any suitable answers to this question.

I hope someone can help, thanks in advance.

window.onload = function(){
    parentDiv.addEventListener('click',function(e){
        alert(e.offsetX);
}, false);
+4
source share
2 answers

getClientRects clientX, :

var offset = this.getClientRects()[0];
alert(e.clientX - offset.left);

DEMO

+4

-, DOM. DOM, Javascript, . , .

, div, , , div. , , , div. , , arg e. . offsetX, , , IE ( Opera), Chrome, Safari Firefox. doc Microsoft, offsetX()" x . , div, , , .

JavaScript, : - JavaScript, , API. , , IE. jQuery - ( ). jQuery normalized .

+3

Source: https://habr.com/ru/post/1532398/


All Articles