E
E
Extramezz2015-11-19 17:10:36
JavaScript
Extramezz, 2015-11-19 17:10:36

How to get the position of an element relative to its parent?

You can get the position of an element relative to the document using $(elem).offset().top, but how can you get the position of an element relative to its parent? Given that the parent at the time of execution

1) May be scrolled, for example, to the middle
2) May lie in several scrolling blocks, which may also already be scrolled.

How to calculate?

jsfiddle.net/jm246q1u/1

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Demidov, 2015-11-19
@Extramezz

https://api.jquery.com/position/

M
Maxim Martirosov, 2015-11-19
@kalbac

(function( $ ) {
 $(selector).each(function( index ) {
  var _self = $(this),
        _parent = _self.closest(parent_selector),
        _offset_self = _self.offset().top,
        _offset_parent = _parent.offset().top,
        _difference = parseInt( _offset_self - _offset_parent );
      console.log( _difference );
 });
})(window.jQuery);

I think you’ll get torn further on what to do with_difference

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question