I'm developing a one-page website, when user clicks a particular button it should be scrolled down to another section on the page.
Can anyone guide me how to do that?
I think the CSS property scroll-padding-top is your answer.
The first approach is to use only HTML to scroll to the element with an specific id
html{height:3000px;scroll-behavior: smooth;}
#readmore{position:absolute; top:2000px;}
<a href="#readmore">Scroll down</a>
<h1 id="readmore">
Read More
</h1>
The second approach is to use scrollIntoView method, which scrolls the specified element into the visible area of the browser window.
const element = document.getElementById("readmore");
document.getElementById('btn').addEventListener('click', () => {
element.scrollIntoView();
})
html{height:3000px;scroll-behavior: smooth;}
#readmore{position:absolute; top:2000px;}
<button id="btn">Scroll down</button>
<h1 id="readmore">
Read More
</h1>
The third approach is to hard code the specific location where I would like to scroll, in this case I set it to 2000px (height)
const element = document.getElementById("readmore");
document.getElementById('btn').addEventListener('click', () => {
window.scrollTo(0, 2000);
})
html{height:3000px;scroll-behavior: smooth;}
#readmore{position:absolute; top:2000px;}
<button id="btn">Scroll down</button>
<h1 id="readmore">
Read More
</h1>