Answer the question
In order to leave comments, you need to log in
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
(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);
_difference
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question