0

I have different sections with different id's and want to scroll to them. I did it with document.getElementById(id).scrollIntoView(), but then the view will scroll in the middle of the div and not to the beginning. I would prefer a solution with no jquery. So the simplified code looks like this:

CSS

#id1 {
        height: 200vh;
        background: black;
      }
#id2 {
        height: 200vh;
        background: yellow;
      }

HTML

<section id="id1">
   <div href="" (click)="scrollTo('id2')">
</section>
<section id="id2">
   <div href="" (click)="scrollTo('id1')">
</section>

Javascript

scrollTo(id) {
    document.getElementById(id).scrollIntoView({
      behavior: "smooth"
    });
Patrick
  • 67
  • 1
  • 9
  • [Element.scrollIntoView](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) should automatically align with the top of the element, but try adding `block: "start"` in the function parameters (right after behavior). If that doesn't work, it could be an incompatibility issue with your browser since `scrollIntoView` is still experimental. – Rai Nov 18 '18 at 21:38

1 Answers1

1

Add block: 'start' to your scrollIntoView options

function scrollToA(id) {
  document.getElementById(id).scrollIntoView({
    behavior: "smooth",
    block: "start"
  });
}
#id1 {
  height: 200vh;
  background: black;
}

#id2 {
  height: 200vh;
  background: yellow;
}

div {
  width: 100%;
  height: 100%;
}
<section id="id1">
  <div onclick="scrollToA('id2')"></div>
</section>
<section id="id2">
  <div onclick="scrollToA('id1')"></div>
</section>
Itay Gal
  • 10,706
  • 6
  • 36
  • 75