skip to Main Content

I have a div inside which there are divs of different heights. The height of these inner divs makes the whole page vertically scrollable which is expected.

Each inner div occupies the width of the screen, hence these inner divs are horizontally scrollable.

Above the outer div, I have buttons (same as the number of inner divs), clicking on which, the corresponding div is scrolled into view.
Here’s the function:

navigateToTab(idx){
 doc = document.getElementById('inner_div_' + idx)
 doc.scrollIntoView({ behavior: "auto", block: "nearest", inline: "start" })
}

This function works, as expected, the inner div for which the button was clicked is scrolled into view.

However, if the inner div’s height is more than the available height, scrollIntoView() aligns the top of the inner div with the top of the window but I want to always stay at the top of the window.

Refer to this diagram to understand the UI a bit better.

I did try to put window.scrollTo({top: 0, left: 0, behavior: 'auto}) but it didn’t work.

I want to always stay at the top of the window no matter which inner div I scroll into view.

2

Answers


  1. You can use the CSS property "position: sticky" for the inner divs to make them remain at the top of the page when scrolled into view.

    Position: sticky will make the inner div elements more like a navigation bar or menu and it will stay in view even when the user scrolls vertically and horizontally.

    You can use the code below to apply the CSS property to the inner divs.

    #inner_div_1
    {
     position: sticky;
     top: 0;
    }
    
    Login or Signup to reply.
  2. You can change your code as follows to ensure that while using scrollIntoView, the top of the inner div is always aligned with the top of the window:

    navigateToTab(idx) {
      const doc = document.getElementById('inner_div_' + idx);
      const rect = doc.getBoundingClientRect();
      window.scrollTo({
        top: window.pageYOffset + rect.top,
        left: 0,
        behavior: 'auto'
      });
    }
    

    In the modified code, the getBoundingClientRect function is used to retrieve the position of the inner div relative to the viewport. The rect.top value represents the distance between the top of the viewport and the top of the inner div.

    By adding window.pageYOffset to rect.top in the window.scrollTo call, the scroll position will be adjusted to ensure that the top of the inner div is always aligned with the top of the window.

    This way, no matter the height of the inner div, it will be scrolled into view with its top edge aligned with the top of the window.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search