2

I am creating an app using Angular2+ where I would like to smooth scroll to an input then set the focus to that input. I am doing something like this:

 scroll(id){
    document.getElementById(id).scrollIntoView({block: "start", behavior: "smooth"});
    document.getElementById(id).focus();
  }

The smooth scrolling part works fine until I add the focus code. I think what is happening is that when I set the focus it overrides the scrolling effect. How can I let the scrolling finish before I set the focus?

Here is code demonstrating what I mean: https://stackblitz.com/edit/angular-t4ousw

ahat91
  • 546
  • 1
  • 6
  • 10

1 Answers1

2

Update: apparently this solution does not work in all browsers

Perhaps there's something preventing you from using this solution, but you can achieve this by simply reversing the order of your method calls. Focus first then execute scroll into view.

scroll(id){
  document.getElementById(id).focus();
  document.getElementById(id).scrollIntoView({block: "start", behavior: "smooth"});
}

For the end user, I imagine the combined effect is the same regardless.

John
  • 9,249
  • 5
  • 44
  • 76
  • 1
    That does not seem to do it for me, when I set the focus then the page jumps to that element. When I then try to scroll to it it looks odd and does not scroll properly. – ahat91 Feb 08 '18 at 22:21
  • @ahat91 Interesting, that must be browser specific. On my mac in Chrome 63, focus does not shift the view at all and scrolling proceeds fluidly. I don't know of a better solution then, sorry. – John Feb 08 '18 at 22:23
  • @ahat91 actually another solution that might work would be to monitor the browser windows scroll event and, when scrolling stops, focus on the element in question. If the page doesn't need to scroll at all, and hence is not scrolling when you perform the scroll check, you could simply focus on the element. Other S.O. questions have more information on how to check window scrolling. e.g. https://stackoverflow.com/questions/12522807/scroll-event-listener-javascript – John Feb 08 '18 at 22:54
  • Just pass the `preventScroll` option to `focus()`. – Drazen Bjelovuk May 12 '21 at 23:06