user3386779
user3386779

Reputation: 7175

get the position of the child div in jquery

I want to get the position of the child div 'test1'.I want to get the left position from parent div.the distance between parent div and child div is '10px' I want t get 10 pixel.Now It prints 140px(calculates from the screen starting position) .

jQuery(document).ready(function($) {
  $('.test1').click(function() {
    var p = $(this);
    var position = p.position();
    console.log(position);
  });
});
.test1 {
  float: left;
  background-color: yellow;
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width:100%">
  <div style="width:250px;background-color:red;padding:10px;margin:auto auto;height:100px" class="testParent">
    <div class="test1">one</div>
    <div class="test1">two</div>
    <div class="test1">three</div>
    <div class="test1">three</div>
    <div class="test1">three</div>
  </div>
</div>

Upvotes: 0

Views: 124

Answers (1)

Abhishek Pandey
Abhishek Pandey

Reputation: 13558

Add position:relative; to parent element, then position() will return position relative to the parent element.

The .position() method allows us to retrieve the current position of an element relative to the offset parent.

Source

jQuery(document).ready(function($) {
  $('.test1').click(function() {
    var p = $(this);
    var position = p.position();
    console.log(position);
  });
});
.test1 {
  float: left;
  background-color: yellow;
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width:100%">
  <div style="position:relative;width:250px;background-color:red;padding:10px;margin:auto auto;height:100px" class="testParent">
    <div class="test1">one</div>
    <div class="test1">two</div>
    <div class="test1">three</div>
    <div class="test1">three</div>
    <div class="test1">three</div>
  </div>
</div>

Upvotes: 1

Related Questions