I have links with the following syntax:
<div class="footer">
<a href="page#link1">Link 1</a>
<a href="page#link2">Link 2</a>
<a href="page#link3">Link 3</a>
</div>
When I'm on the http://example.com/page
and I click on any of the 3 links, it doesn't jump to the top of the page.
However, it jumps if the link is something like this:
<a href="#">Link 1</a>
How should I make it scroll/jump to the top when any of the links are clicked?
You can set up a click event handler for all the elements you want to cause the scroll to occur using window.ScrollTo()
like this:
// Get a node list of all the elements that use the footer class var footers = document.querySelectorAll(".footer"); // Loop through the footers and set up a click event handler for each for(var i = 0; i < footers.length; i++){ footers[i].addEventListener("click", function(e){ // Scroll to the top of the page: window.scrollTo(0, 0); }); }
<a href="page#link1"><div class="footer">Link 1</div></a> <a href="page#link2">Link 2</a> <a href="page#link3"><div class="footer">Link 3</div></a>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.