Please, enter a valid email!
00 days
:
00 hours
:
00 minutes
:
00 seconds

Creating a Back to Top jQuery Button with CSS

A back to top jQuery button is something that a lot of you have probably seen on many websites. It’s that arrow that appears at the bottom right corner of a web page when you start scrolling it. When clicked, it brings you back to the top of the page.

back to top jquery

If you want to add a back to top button while you're still building a website, or just curious about how you can build one on your own, welcome aboard!


Back to Top jQuery Button

Our code would consist of two parts, the CSS styling and a small jQuery script. Let’s start with CSS.

CSS Styles for the back to top jQuery Button

We start off by creating styles and markup for our button. Here’s the HTML part:


<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

<a id="button"></a>

The button would consist of only one anchor tag with an id button. We also include a link to the FontAwesome library so that we can use an icon for our button.

The initial styles for the button would look like this:


#button {
  display: inline-block;
  background-color: #FF9800;
  width: 50px;
  height: 50px;
  text-align: center;
  border-radius: 4px;
  margin: 30px;
  position: fixed;
  bottom: 30px;
  right: 30px;
  transition: background-color .3s;
  z-index: 1000;
}
#button:hover {
  cursor: pointer;
  background-color: #333;
}
#button:active {
  background-color: #555;
}

Since the button is an anchor element, and anchors by default are inline elements, we need to change the display property to inline block so that we can assign dimensions to it.

Let’s make it a square button of 50*50px with rounded corners of 4px. We’ll give it a bright orange color and a margin of 30px on each side.

The fixed position would always enable our button to stay at the same spot when we scroll the page, and z-index of a very high number makes sure that the button is always overlapping other website elements.

When we hover over a button the cursor changes to a pointer, and the background becomes a dark grey. In order to make the transition smooth, we assign the transition of 0.3 seconds to the background-color property. Also, when we click the button, the background color also changes and becomes a bit lighter.


Adding an Icon

Right now our button is empty, so let’s add an icon to it. We do it by adding an ::after pseudo-element like this:


#button::after {
  content: "\f077";
  font-family: FontAwesome;
  font-weight: normal;
  font-style: normal;
  font-size: 2em;
  line-height: 50px;
  color: #fff;
}

We’re going to pick an icon from the most popular font library FontAwesome. I decided to go with a Chevron Up icon.

In order to display it in a pseudo-element, set the font-family to FontAwesome, and assign the Unicode value of your icon to the content property.

Also make sure that your line height is equal to the height of your icon if you want it to be centered horizontally.


Adding Functionality with jQuery

In this sub-section I'll actually show you how to make the button work as expected. The easiest way to achieve this is to use a JavaScript library jQuery. First, we have to add jQuery to the HTML markup of our code. Add this line of code just before the closing body tag.


<script src=”https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js”></script>

Now we can write our script using jQuery syntax. Add the following script after the jQuery line:


<script>

jQuery(document).ready(function() {
  
  var btn = $('#button');

  $(window).scroll(function() {
    if ($(window).scrollTop() > 300) {
      btn.addClass('show');
    } else {
      btn.removeClass('show');
    }
  });

  btn.on('click', function(e) {
    e.preventDefault();
    $('html, body').animate({scrollTop:0}, '300');
  });

});

</script>

Let’s take a closer look at this script.

You will notice the first line of code:


jQuery(document).ready(function() {

It is basically saying, run the code inside this function only when the document is fully loaded. This is a great way to prevent errors, in case your JavaScript code wants to make changes to parts of a web page which are not fully loaded in the browser.

The code that we run after the document is fully loaded consists of two major chunks of code where each one is doing its own thing.

The first part of the script makes our button appear and disappear after the page scroll reaches a certain point. The second part makes the page scroll to the top after we click the button. Let’s examine each one in detail.


Making the Button Appear and Disappear

This is the code that does the trick:


var btn = $('#button');

  $(window).scroll(function() {
    if ($(window).scrollTop() > 300) {
      btn.addClass('show');
    } else {
      btn.removeClass('show');
    }
  });

First we declare a variable btn and point it to an element with an ID of button, so that it will be easier for us to refer to it later in the code. Also this helps JavaScript to make calculations faster. Once we store the element in a variable, JavaScript won’t need to search through the whole page over and over each time we need to use it again in our code.


.scroll()

jQuery has a handy function .scroll(). What it does is bind a piece of code that will be executed each time that a scroll event on your web page happens. It takes one parameter, which is a function that is being executed each time when you do a page scroll. Although you can apply it to any scrollable element, such as frames and elements with overflow property set to scroll, usually we apply it to the window element, since that’s where the scrolling occurs in most cases, including our example.


$(window).scroll(function() {

Inside the function we place this if/else statement:


    if ($(window).scrollTop() > 300) {
      btn.addClass('show');
    } else {
      btn.removeClass('show');
    }

What we’re trying to do here is check the vertical position of the scroll bar, and make our button appear when it is below a certain point, and disappear when it is above that point.

In order to get the current position of the scroll bar, we’re going to use a built-in jQuery method .scrollTop(). It doesn’t take any arguments, and simply returns a number of pixels that is hidden above the scrollable area.

So, each time we do a scroll, JavaScript checks how many pixels are hidden, and compares them to a number. In our case I set that number to 300, but you can change it if you want.

If we go past 300px, then we add a class show to our button element, which would make it appear. If the number is less than 300, we remove that class. Adding and removing classes is another reason why jQuery is so popular. We can do it with two simple methods addClass() and removeClass().

However we don’t have the show class in our CSS yet, so let’s add it:


    if ($(window).scrollTop() > 300) {
      btn.addClass('show');
    } else {
      btn.removeClass('show');
    }

By default our button is going to be hidden, so we would need to add a few more rules to the #button element:


#button {
  transition: background-color .3s, 
    opacity .5s, visibility .5s;
  opacity: 0;
  visibility: hidden;
}

In order to make the transition smooth, I’ve added two more values to the transition attribute, opacity and visibility set to 0.5 seconds.


Scroll to the Top

The second part of the script enables you to scroll to the top of the page after clicking the button.


  btn.on('click', function(e) {
    e.preventDefault();
    $('html, body').animate({scrollTop:0}, '300');
  });

The first jQuery method we see here is on(). Its first parameter is the ‘click’ JavaScript event, which occurs each time when we do a mouse click in our browser. The second parameter is a handler function, which is triggered as soon as the event occurs.

The handler function takes an event parameter. We can name it whatever we want, but usually e or event are preferred. We need the event parameter in order to pass it to the function and use for the preventDefault() method.

The method e.preventDefault() prevents the default action of the event from happening, for example a link doesn’t take us to the next page. In our case it’s not crucial, since our anchor element lacks the href attribute and wouldn’t take us to a new page anyway, but it’s always better to double-check.


.animate()

The jQuery .animate() method is the one that does the whole trick.


$('html, body').animate({scrollTop:0}, '300');

The first parameter of the .animate() method is the list of properties which we should animate. Our property is called scrollTop, and we want it to have a value of 0. The type of this parameter is plain object and that’s why we need to use curly braces and write down our values using the key/value pair syntax.

The second parameter is the speed with which we want our animation to run. It is measured in milliseconds and the higher the number, the slower the animation. The default one is 400, but I changed it to 300.

Finally, we apply the animate method to the HTML and body elements on our web page.

Now each time we click the button, it will take us to the top of the page.

See the Pen
Back to Top Button
by Matthew Cain (@matthewcain)
on CodePen.

You can see the final result in this CodePen demo. I’ve also included some sample text up there for demonstration purposes.


Final Thoughts

Back to top buttons are a great usability element of a web page, and having one on your website adds a small but helpful detail most of us are used to. Hopefully this guide has helped you broaden your CSS and JavaScript knowledge, providing some ‘a-ha’ moments that can be so useful for aspiring website templates designers and developers.

Keep on hacking!


FAQ

What is a back to top button?

It is an arrow-shaped icon that usually is placed to the bottom right corner of the screen. When you hit it – the page scrolls up to the top.

Why do I need a back to top button?

It is really convenient for the user, especially if the page is long and contains lots of content. A back to top button improves the user experience and make visiting your site more pleasant for the person.

How the back to top button is made?

It consists of a CSS design part and a little jQuery script that makes it work.


Read Also

Photo Gallery for Your HTML5 Website – jQuery and CSS3 Tutorials

How to Build a Slide-Out Navigation Menu With CSS & jQuery

Hidden Click-To-Expand Paragraph Text with jQuery

Custom CSS3 & jQuery Toggle Search Form: Tutorial


Matthew Cain

I like to create websites from the ground up, coding them carefully with HTML and CSS. Sometimes even the best and professionally created templates need some coding tricks. And here is my Quora account.

Get more to your email

Subscribe to our newsletter and access exclusive content and offers available only to MonsterPost subscribers.

From was successfully send!
Server error. Please, try again later.

33 responses to “Creating a Back to Top jQuery Button with CSS”

  1. CalvinSal says:

    canadian pharmacy ltd canadian pharmacy ltd

  2. CalvinSal says:

    cheapest pharmacy for prescriptions without insurance cheapest pharmacy for prescriptions

  3. MichaelDaymn says:

    tadalafil without a doctor’s prescription pain meds online without doctor prescription

  4. MichaelDaymn says:

    prescription drugs canada buy online ed meds online without doctor prescription

  5. Josephken says:

    buy ciprofloxacin over the counter ciprofloxacin

  6. Josephken says:

    lisinopril 10mg tabs lisinopril 3.5 mg

  7. Having read this I believed it was really informative.
    I appreciate you taking the time and energy to
    put this short article together. I once again find myself spending way too much time both reading and leaving comments.

    But so what, it was still worth it!

  8. Deshawnbrelo says:

    buy valtrex tablets cheap valtrex generic

  9. Davidtot says:

    ed prescription drugs online canadian pharmacy

  10. Davidtot says:

    non prescription ed pills amoxicillin without a doctor’s prescription

  11. buy nolvadex online nolvadex australia where can i buy nolvadex online how long can you take nolvadex

  12. Jameswap says:

    [url=https://drugsbestprice.com/#]treating ed[/url] ed and diabetes

  13. WilliamMic says:

    stromectol for humans for sale stromectol 12 mg tablets

  14. DarrellSew says:

    doxycycline buy doxycycline

  15. DarrellSew says:

    clomid 50 mg buy uk clomid 100mg for sale

  16. GeorgeMum says:

    https://cipro.best/# cipro online no prescription in the usa

  17. magnificent post, very informative. I ponder why the other experts of this sector do not realize this.
    You should continue your writing. I’m confident, you’ve a
    huge readers’ base already!

  18. Isiahvaphy says:

    ed meds online canada canada ed drugs

  19. HomerInent says:

    cost of tamoxifen who should take tamoxifen

  20. EdwardGet says:

    lasix 100 mg furosemide 40mg

  21. HomerInent says:

    lasix medication buy lasix online

  22. page says:

    Hello there! Do you use Twitter? I’d like to follow you if that would be ok.
    I’m absolutely enjoying your blog and look forward to new updates.

  23. judi online says:

    I’m extremely impressed with your writing skills and also with the layout on your weblog.
    Is this a paid theme or did you customize it yourself?
    Anyway keep up the excellent quality writing, it is rare to see a great blog like this one today.

    Feel free to visit my web site: judi online

  24. Jodie Watson says:

    There’s just one thing I’ve noticed with your example…

    If you’re going to pass the animation speed through as a number you need to remove the quotes to stop it being treated as a string.
    Otherwise it’s only the keywords that will work… e.g. “slow”, “fast”

    If you wish to use a number for the speed just call it like this: $(‘html, body’).animate({scrollTop: 0}, 3000)

  25. Alexander says:

    Tnx! This was very helpful! 😉

  26. Ahsan Habib says:

    Really effective way to add back to top button. It will be so useful for any landing page template.

  27. hi Matthew,
    just trying to add your code (js, css) to my RapidWeaver CMS. RapidWeaver allows for adding various codes that will then be valid for all pages of that site. I assuming that jquery is already loaded and defined by the template (theme) I am using. The same should be the case with fontawesome.
    Then if I am right there must be an anchor HTML element on every single page to let the button work. This could be a tricky one because custom HTML would be placed at the very end of a page and adding it into the HEAD wouldn’t work I expect.
    But for now eben the button wouldn’t be displayed 🙁
    I’ve set up a test and development site as a subdomain http://new.uhebeisen.net
    There this code ist uploaded. But only the page “hobby” has the HTML code placed near the top.
    It would be really nice to get this scroll-to-top working on the whole project. If you can have a look at it maybe you see and tell me where I am wrong.
    Thanks
    ueli

Leave a Reply

Your email address will not be published. Required fields are marked *