Prevent scrollIntoView() from scrolling the container to the top of the page
P粉690200856
P粉690200856 2024-03-26 20:25:28
0
1
446

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粉690200856
P粉690200856

reply all(1)
P粉976737101

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',
    });
  });
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template