Add a Floating Back-to-Top Button

Implement a floating “Back to Top” button that appears when users scroll down.

<?php
function add_back_to_top_button() {
    echo '<a href="#" class="back-to-top">↑</a>';
    echo '<style>
        .back-to-top {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: #000;
            color: #fff;
            padding: 10px;
            border-radius: 5px;
            text-align: center;
            display: none;
        }
        .back-to-top:hover {
            background: #333;
        }
    </style>';
    echo '<script>
        jQuery(document).ready(function($) {
            $(window).scroll(function() {
                if ($(this).scrollTop() > 200) {
                    $(".back-to-top").fadeIn();
                } else {
                    $(".back-to-top").fadeOut();
                }
            });
            $(".back-to-top").click(function() {
                $("html, body").animate({scrollTop : 0},800);
                return false;
            });
        });
    </script>';
}
add_action('wp_footer', 'add_back_to_top_button');

Post Comment