Thursday, 8 September 2016

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'.

    <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=”//”></script>

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

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 [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.

        var isVisible = false;
        $(window).scroll(function () {
            var shouldBeVisible = $(window).scrollTop() > 300;
            if (shouldBeVisible && !isVisible) {
                isVisible = true;
            } else if (isVisible && !shouldBeVisible) {
                isVisible = false;

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.

No comments:

Post a comment