0

I am looking for way to make page scroll on menu click.

My found place where to go. When I use translateY it work(but ofcouse I can't use it). I need a scroll I tried to use scrollTop and scrollBy but it doesn't work for me. What I do wrong?

function scroll(id: number) {
            for (let k = 0; k < sectionsForScroll.length; k++) {
                if (sectionsForScroll[k].dataset.navId == id) {
                    const bigginer = sectionsForScroll[0].getBoundingClientRect().top;
                    console.log( bigginer + 'px  how far we from the start ');
                    const distanceToGo= sectionsForScroll[k].getBoundingClientRect().top;
                    console.log(sectionsForScroll[k].offsetTop);
                    const distanceToScroll = bigginer - distanceToGo;
                    console.log(distanceToGo + ' where we have to go ');
                    console.log(distanceToScroll + ' what the distanse we need to scroll ');
                    main.style.transform = 'translateY(' + distanceToScroll + 'px)';
                    // main.scrollTop=distanceToGo;
                    // window.scrollBy(0, distanceToGo);
                }
            }
        }
Noa
  • 424
  • 1
  • 3
  • 16

1 Answers1

0

window.scroll will work for you. Here is an example of scrolling 300px after clicking the scroll button.

Before using it you should checkout the compatibility table for the smooth option.

document.getElementById("myButton").addEventListener("click", scrollMe);

function scrollMe() {
  window.scroll({
    top: 300,
    left: 0,
    behavior: 'smooth'
  });
}
.myDiv {
  background-color: green;
  height: 1000px;
}
<div class="myDiv">
  <button id="myButton">Scroll</button>
</div>
Andrew Lohr
  • 5,380
  • 1
  • 26
  • 38