This simple snippet adds a floating “Back to Top” button that appears when users scroll down the page. The button smoothly scrolls back to the top when clicked, improving user experience and navigation.
The snippet creates a circular floating button with an arrow icon that appears in the bottom-right corner when users scroll down more than 300 pixels. Clicking the button smoothly scrolls back to the top of the page.
/**
* Add smooth back to top button to website
* Simple floating button that appears when scrolling down
* Prefix: tpsc_ (TP Snippet Collection)
*/
// ============================================
// ADD BACK TO TOP BUTTON HTML
// ============================================
// Add button to footer
add_action('wp_footer', 'tpsc_add_back_to_top_button');
function tpsc_add_back_to_top_button() {
echo '<div id="tpsc-back-to-top" title="Back to Top">
<span class="tpsc-arrow">↑</span>
</div>';
}
// ============================================
// ADD CSS STYLES
// ============================================
// Add CSS for the button
add_action('wp_head', 'tpsc_back_to_top_styles');
function tpsc_back_to_top_styles() {
echo '<style>
#tpsc-back-to-top {
position: fixed;
bottom: 30px;
right: 30px;
width: 50px;
height: 50px;
background-color: #333;
color: white;
border-radius: 50%;
text-align: center;
line-height: 50px;
cursor: pointer;
opacity: 0;
visibility: hidden;
transition: all 0.3s ease;
z-index: 9999;
box-shadow: 0 2px 10px rgba(0,0,0,0.3);
}
#tpsc-back-to-top:hover {
background-color: #555;
transform: translateY(-3px);
box-shadow: 0 4px 15px rgba(0,0,0,0.4);
}
#tpsc-back-to-top.show {
opacity: 1;
visibility: visible;
}
.tpsc-arrow {
font-size: 20px;
font-weight: bold;
}
/* Mobile responsive */
@media (max-width: 768px) {
#tpsc-back-to-top {
bottom: 20px;
right: 20px;
width: 45px;
height: 45px;
line-height: 45px;
}
.tpsc-arrow {
font-size: 18px;
}
}
</style>';
}
// ============================================
// ADD JAVASCRIPT FUNCTIONALITY
// ============================================
// Add JavaScript for scroll behavior
add_action('wp_footer', 'tpsc_back_to_top_script');
function tpsc_back_to_top_script() {
echo '<script>
document.addEventListener("DOMContentLoaded", function() {
var backToTopButton = document.getElementById("tpsc-back-to-top");
// Show/hide button based on scroll position
window.addEventListener("scroll", function() {
if (window.pageYOffset > 300) {
backToTopButton.classList.add("show");
} else {
backToTopButton.classList.remove("show");
}
});
// Smooth scroll to top when clicked
backToTopButton.addEventListener("click", function() {
window.scrollTo({
top: 0,
behavior: "smooth"
});
});
});
</script>';
}
Something not working as expected? Need help customizing it for your specific needs?
Have an idea for functionality you're missing on your site? Tell us what you're looking for!
Share it with us! Our community loves learning and growing together.
No comments yet.