Sometimes, we want to scroll element to top of page by clicking anchor inside element or anywhere inside containing div ID with JavaScript.
In this article, we’ll look ay how to scroll element to top of page by clicking anchor inside element or anywhere inside containing div ID with JavaScript.
How to scroll element to top of page by clicking anchor inside element or anywhere inside containing div ID with JavaScript?
To scroll element to top of page by clicking anchor inside element or anywhere inside containing div ID with JavaScript, we can call the scrollTo
method.
For instance, we write:
<button>
scroll
</button>
to add a button.
Then we write:
const button = document.querySelector('button')
button.onclick = () => {
window.scrollTo(0, 0)
}
to select the button with querySelector
.
Then we set button.onclick
to a function that calls window.scrollTo
with 2 0’s to scroll to the top of the page.
Conclusion
To scroll element to top of page by clicking anchor inside element or anywhere inside containing div ID with JavaScript, we can call the scrollTo
method.