CSS: How do I create a single 'back to top' button?

A little CSS and JQuery can produce a lot of magic in an application. Here is the code.

1. Start with a simple html page. The important item here is to have an 'ID' to navigate to. In my case, I called it 'top'.

<html>
<head>
    <base href="/" />
    <title>Test Page</title>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <script src=”//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js”></script>

    <link href="css/myStuff.css" rel="stylesheet" />
</head>
<body>
    <div>
        <!-- Start Body Content -->
        <div ng-view role="main" id="top"></div>
        <!-- End Body Content -->
    </div>
</body>
</html>

2. Create the element you want to perform the navigation

<a id="backtotop" href="" class="back-to-top hidden" onclick="$('html, body').animate({'scrollTop': $('#top').offset().top}, 500);"><span class="icon-arrow-up"></span>Back to Top</a>

3. Add some CSS

.back-to-top{background-color:blue;bottom:64px;box-sizing:border-box;color:#fff;display:block;height:80px;line-height:1.4em;padding:10px 19px;position:fixed;right:40px;text-align:center;width:77px}
.back-to-top:hover{background-color:green}
.back-to-top [class^="icon-"]{display:block;position:relative;top:-1px}
.back-to-top .icon-arrow-up:before{font-weight:bold;font-size:1.5em}

4. Finally, add come code to make it appear when required. This should go in the 'head' of the html.

    <script>
        var isVisible = false;
        $(window).scroll(function () {
            var shouldBeVisible = $(window).scrollTop() > 300;
            if (shouldBeVisible && !isVisible) {
                isVisible = true;
                $('#backtotop').show();
            } else if (isVisible && !shouldBeVisible) {
                isVisible = false;
                $('#backtotop').hide();
            }
        });
    </script>

You are now good to go.The element can be placed in a any page/module. It will appear when the user has scrolled down the page and will return them to the top.

Comments

Popular posts from this blog

SharePoint 2013: Error updating managed account credentials

How can I call a JIRA api through Powershell?