Blog IT

You've probably seen a "back-to-top" button at the bottom-right corner on many websites when you're scrolling around. Clicking on that button takes you back to the top of the page.

This is a great feature to have on any website, and today we are going to see how to build it with nothing but HTML, CSS, and JavaScript.

  1. Code html
    <p id="back-top">
        <a href="#top">
          <i class="fa fa-angle-up"></i>
        </a>
    </p>
  2. Code css
    #back-top {
        bottom: 70px;
        margin-bottom: 0;
        margin-right: 15px;
        position: fixed;
        right: 0;
        z-index: 100;
    }
    #back-top a {
        background-color: #f24976;
        display: block;
        height: 50px;
        outline: medium none;
        position: relative;
        text-indent: 0;
        -webkit-transition: all 0.3s ease-in-out;
        -moz-transition: all 0.3s ease-in-out;
        -o-transition: all 0.3s ease-in-out;
        transition: all 0.3s ease-in-out;
        width: 50px;
        z-index: 0;
        text-align: center;
        line-height: 2;
        color: #fff;
        line-height: 50px;
        border-radius: 50px;
    }
    #back-top a i{
        font-size: 24px;
    }
  3. Code js
    (function ($) {
        'use strict';
                $("#back-top").hide();
                $(function () {
                    $(window).scroll(function () {
                        if ($(this).scrollTop() > 500) {
                            $('#back-top').fadeIn();
                        } else {
                            $('#back-top').fadeOut();
                        }
                    });
                    // scroll body to 0px on click
                    $('#back-top a').click(function () {
                        $('body,html').animate({
                            scrollTop: 0
                        }, 800);
                        return false;
                    });
                });
    })(jQuery);