Search code examples
jqueryoffset

Issue with jquery offset() of the same element within 2 differnet sidebars


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?


Solution

  • Did you try closest method, to find closest ancestor?

    $('.cssClass1, .cssClass2').on('click', function () {
        const position = $(this).closest('.sidebar-inner').find('.sidebar-header').offset();
    
        if (position.top < 0) {
            console.log('unvisible');
        } else {
            console.log('visible');
        }
    });