As I am new to js I can’t solve a problem with offset() by myself.
I got two sidebars – one on the left, the other one on the right. In the DOM, the left one comes first.
Within my sidebars I have the the following structure:
<div class="sidebar-inner">
<div class="sidebar-header">
Some blabla
</div>
<div class="sidebar-content">
More blabla
</div>
<div class="sidebar-footer">
Also some blabla
</div>
</div>
Now I try to get the position of my "sidebar-header" with jquery by clicking an element in my sidebar.
$('.cssClass1, .cssClass2').on('click', function (){
var position = $('.sidebar-header').offset();
if (position.top < 0){
console.log('unvisible');
} else {
console.log('visible')
};
});
With my code, I got the position, but just from my "sidebar-header" which comes first in the DOM (the left sidebar, in this case).
How can I get the position of my "sidebar-header" within the sidebar from where the cssClass element is clicked?
2
Answers
Did you try
closest
method, to find closest ancestor?If there are several elements, then you need to use a
.each()
: