Scroll to Top of the Page by JQuery Animate Example Tutorial

May 09, 2024 | jQuery Javascript HTML


Hello Dev,

If you desire the scrolling process to be accompanied by an animated effect, follow the example below. This post will guide you on adding a button for scrolling to the top of the page with an animate effect. On many websites, you'll notice a button positioned on the left or right side for scrolling to the top of the page. If you wish to implement this feature on your site, you can achieve it by adding the following jQuery code:

Read Also: Bootstrap Dynamic Autocomplete search using Typeahead JS Example Tutorial
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scrolling Top Button</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        /* styles.css */
        .scroll-top-btn {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 99;
            border: none;
            background-color: #333;
            color: white;
            padding: 15px;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            transition: opacity 0.3s ease-in-out;
        }
        .scroll-top-btn.fadeIn {
            opacity: 1;
        }
    </style>
</head>
<body>
<button id="scroll-top-btn" class="scroll-top-btn">Top</button>
<script>
$(document).ready(function() {
    $(window).scroll(function() {
        if ($(this).scrollTop() > 100) {
            $('#scroll-top-btn').fadeIn();
        } else {
            $('#scroll-top-btn').fadeOut();
        }
    });

    $('#scroll-top-btn').click(function() {
        $('html, body').animate({
            scrollTop: 0
        }, 800); // Change 800 to adjust the scrolling speed
    });
});
</script>
</body>
</html>
Output: Scroll to Top of the Page by JQuery Animate Example Tutorial

Thank you for your encouragement! If you have any questions or need further assistance, feel free to ask. I'm here to help!



Tags :
#jQuery
#Javascript
#HTML
ItErrorSolution.com

ItErrorSolution.com

"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"