How to add a simple scroll button to the top of the page/post button without using any plugins.
This was strangely hard to figure out for a beginner I knew as they didn’t understand where to put JavaScript.
So here’s a simple bit of html code you can place into any post/page on your website:
<div class="wp-block-button" onclick="topFunction()"><a class="wp-block-button__link wp-element-button" style="width:100%; border-radius: 0;">↑ Scroll To Top ↑</a></div>
<script>
// Get the button:
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; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
</script>
Just put that into a “Custom HTML” block in your WordPress website and you should have something looking like this:
Or you can add it to your child theme directly and have it automatically displayed at the bottom of any child page.
I however am too lazy to do that at the moment so good luck with figuring it out yourself.