skip to Main Content

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


  1. 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');
        }
    });
    
    Login or Signup to reply.
  2. If there are several elements, then you need to use a .each():

    $(document).on('click', 'button', function(){
      $('.sidebar-inner').each(function(){
        const { top } = $(this).offset();
        console.log(top);
      })
    })
    .page {
      display: grid;
      grid-template-columns: 100px 1fr 100px;
    }
    
    .sidebar-inner:last-child {
      margin-top: 40px;
      align-self: start;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="page">
      <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>
      <main></main>
      <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>
    </div>
    <button>Get Sidebars Offset</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search