8

Anyone know which is the differences between scrollIntoView() vs scrollIntoViewIfNeeded()?

I didn't see the differences between them. They both scroll if the element is not in visible area & do nothing if already visible.

Heyyy Marco
  • 633
  • 1
  • 12
  • 22

2 Answers2

9

If using the scrollIntoView() 'block' parameters 'start' (default), 'center' or 'end' scrollIntoView() always scrolls the element to the specified position even if it's already all on screen.

If using the parameter block: 'nearest' it behaves more like scrollIntoViewIfNeeded(), i.e. nothing happens if it is already on screen

00-BBB
  • 746
  • 7
  • 24
5

Your description is correct.

The Element.scrollIntoViewIfNeeded() method scrolls the current element into the visible area of the browser window if it's not already within the visible area of the browser window. If the element is already within the visible area of the browser window, then no scrolling takes place. This method is a proprietary variation of the standard Element.scrollIntoView() method.

Note: it is also considered non-standard.

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoViewIfNeeded

olore
  • 4,687
  • 3
  • 28
  • 40
  • i know it's non standard. but why the variant there? i didn't experience the different result. same not scrolling when in visible area. – Heyyy Marco May 08 '21 at 09:16
  • 1
    Sounds like you are looking for the reason for its existence. My guess is that it was implemented before the standard and simply hasn't been removed yet and they gave the standard one a nicer name. – olore May 08 '21 at 12:27
  • 1
    so, the scrollIntoViewIfNeeded is now obsolete? ok i'll use the standard one. – Heyyy Marco May 12 '21 at 11:19
  • scrollIntoView() is bugged in some cases (when no scrolling would have been needed). Seems like it won't be fixed anymore, maybe they bugged the specification. See https://stackoverflow.com/questions/11039885/scrollintoview-causing-the-whole-page-to-move – knallfrosch Feb 23 '22 at 21:06