1

I have structure:

<div class="parent"> 
   <div class="child"> 
   </div>
<div>

I have jquery binded click

$('div.parent').bind('click', function(e) { e.offsetX }); 

chid is centered, when I click it, I have e.offsetX of child not parent. How can I get parent offsetX, if clicking on child element?

I want to always get parent e.offsetX

I mean event.click offset, not container offset

Pikachu
  • 1,973
  • 3
  • 20
  • 27

2 Answers2

1

Try this:

var offset = $(this).closest("div").css("offsetX");

like this the var offset will have the value of the parents div offset.

UPDATE:

$("#something").click(function(e){
   var childOffset = $(this).offset();
   alert(e.pageX - e.childOffset);
});

By subtacting the child offset from the entire offset you get the parent offset.

Vítor Martins
  • 1,430
  • 4
  • 20
  • 41
1

In your code:

$('div.parent').bind('click', function(e) {
  alert(e.offsetX); // gives the offsetX of the click not the parent div
});

e.offsetX denotes the offsetX of the click happened on parent div. I guess you want the offsetX of the dom node/jquery object which in case is parent div.

$('div.parent').on('click', function(e) { // use .on() instead
  alert($(e.target).offset().left); // $(e.target).offset().left will give you offsetX.
});

$('div.parent').on('click', function(e) {
  alert('left : '+ $(e.target).offset().left + "top : "+$(e.target).offset().top);
});
.parent {
  width: 200px;
  height: 200px;
  background: red;
  margin:0 auto;
}
.child {
  width: 100px;
  height: 100px;
  background: yellow;
  margin:0 auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  <div class="child">
  </div>
  <div>
Jai
  • 74,255
  • 12
  • 74
  • 103