Press "Enter" to skip to content

jQuery: scroll to top button

I will show in this short article how to add “scroll to top” button or arrow. This is a popular solution used on blogs or “one page” websites – so in situation when web page has a long content, which require a lot of scrolling, then user has easy option to go smoothly to top of the website.

There are many methods to achieve that, but here we focus on scroll to top button/arrow build with jQuery library.

First we need to add HTML code with button, like below. Button code is wrapped with link “a” tag. This is for the accessibility purpose – user using only keyboard must have possibility to press that button too. Next we have div with class “scroll-top-btn” and next is span tag with text. This is also because the accessibility purpose – reader browsers must have some text in link “a” tag to read it for users with eye problems. But text in span is hidden, what you can see further, in CSS code.

<a href="#">
  <div class="scroll-top-btn">
    <span>Scroll to top</span>
  </div>
</a>

Next we need to define a CSS styles for scroll to top button. We will not use here images – all shapes will be drawn within CSS. So just copy and paste this CSS code into your code. For that purpose we use a CSS para element “before”. This scroll to top arrow will display in fixed position in bottom right corner of the page.

.scroll-top-btn {
    position: fixed;
    bottom: 50px;
    right: 20px;
    background: rgba(50,50,50,0.5);
    width: 40px;
    height: 40px;
    border-radius: 5px;
}

.scroll-top-btn span {
    visibility: hidden;
}

.scroll-top-btn::before {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    content: '';
    width: 0;
    height: 0;
    border-left: 15px solid transparent;
    border-right: 15px solid transparent;
    border-bottom: 25px solid rgba(255,255,255,0.9);
}

Next, if you do not have, you need to add jQuery to our website and copy and paste from here JavaScript code with “scroll to top” functionality. It is very basic – only 4 lines of code. We need to handle onclick event on our button, prevent the default behavior, and scroll to page top with animation in time of 500 milliseconds.

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script defer>
  $(".scroll-top-btn").click(function (e) {
    e.preventDefault();
    $('html, body').animate({ scrollTop: 0}, 500);
  });
</script>

This solution will work without any problems in all browsers, event very old like IE 11.

You can download the demo here: scroll to top button example or check above code on our Gitlab account HERE.

Check the same demo example in frame below:

THE END 🙂