I easily got this to work with the W3schools tutorial “How To Create a Scroll Back To Top Button”.
Problem: I have 3 to 4 tabs on one page.
In the W3schools example it works with let mybutton = document.getElementById("myBtn");
which works for the first tab, not for the others.
I think I need a different ID for each tab.
How can I do this???
Btw.: heres the full script:
<script>
// Scroll to Top
let mybutton = document.getElementById("myBtn");
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
</script>
There’s nothing here that should necessitate the button being a part of your tabs. There should be just one button on the page, located outside of your tab structure (probably appended to the end of the page.