search

Home  >  Q&A  >  body text

Prevent scrollIntoView() from scrolling the container to the top of the page

I'm trying to build a simple "mainly css" image carousel that uses scroll snapping but also has navigation buttons to control the currently viewed slide. The only solution I've found is to use scrollIntoView() on the target element, which does what I want, but it also always scrolls the target element to the top of the page. I want the target carousel to be magic%E

P粉690200856P粉690200856241 days ago449

reply all(1)I'll reply

  • P粉976737101

    P粉9767371012024-03-27 18:41:09

    Try adding block: 'nearest' to your scrollIntoView options like this:

    document.querySelectorAll('button').forEach(button => {
      button.addEventListener('click', event => {
        console.log('event',event);
        slides[event.target.dataset.index].scrollIntoView({
          behavior: 'smooth',
          inline:   'center',
          block:    'nearest',
        });
      });
    });
    

    reply
    0
  • Cancelreply