Scroll To Top Button JavaScript Tutorial for WordPress

📂 Category: PHP

🖺 Last modified: 8th Dec 2021

💻 Experience: Intermediate

🕑 Read Time: 6 min

The Scroll To Top Button nowadays became a standard on all websites with a lot of content on posts or pages. It keeps visitors on the website and lowers bounce rate by allowing them to quickly jump back to the header navigation and continue browsing your site. If you decided to add this feature to your WordPress website, we suggest a using a simple JavaScript code described in this tutorial.

Why should you JavaScript to create a Scroll To Top Button in WordPress?

There are a dozen of free Scroll To Top Button WordPress plugins currently available. Most of them work out of the box and do their job quite well. There are also plenty of possibilities to customize their look and behavior. So why should you bother to manually code your JavaScript button with all those ready made options available?

Firstly, many developers don’t like to use too many plugins. Specially when there’s a possibility to solve the task with a simple script. The Scroll To Top Button JavaScript code is very simple, configurable and easy to add to any website.

Secondly, all Scroll To Top Button WordPress plugins are based on heavier jQuery scripts, and depending of their configuration, they generate additional server requests that affect your website loading speed. In the other hand, a pure JavaScript Scroll To Top Button won’t generate additional server requests and it won’t impact the loading speed at all. Now that loading speed matters more and more in web development and SEO optimization, everyone should take it in consideration and keep their websites as fast as possible.

 

Adding the Scroll To Top Button JavaScript code to WordPress websites

The Scroll To Top Button in our example consists of three parts:

  • HTML <button> element
  • JavaScript <script> that runs the button
  • CSS properties defining the visual appearance of the button

Since we’re implementing the Scroll To Top Button into a WordPress website, we need to add those three parts of code into specific positions of WP template files. We’ll add the HTML button element and the JavaScript code on the very bottom of the footer.php file, right before the closing </body> tag. Accordingly, the CSS code goes into our theme’s stylesheet, usually called style.css.

Pro Tip:Template files are located within the WP Dashboard’s theme editor inside the Appearance tab. When editing template files, the best practice would be to create and use Child Themes. That way all the changes you made to template files won’t get lost in case you’re updating the main theme.

Firstly, let’s add the Scroll To Top Button code to our website, then we’ll analyze the code and explain how it works and how to customize it.

<button onclick="BackTop()" id="backtop-button" title="Back To Top"><span>&#9650;</span>Back Top</button>

<script>
var BackTopButton = document.getElementById("backtop-button");

window.onscroll = function() {ScrollOffset()};

function ScrollOffset() {

  if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
    BackTopButton.style.visibility = "visible";
    BackTopButton.style.opacity = "0.7"; 
    BackTopButton.style.pointerEvents = "initial"; 
  } 
    
  else {
    BackTopButton.style.opacity = "0";
    BackTopButton.style.pointerEvents = "none";
  } 
}


function BackTop() {
  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
}
</script>
html { scroll-behavior: smooth; }

#backtop-button {
    display: block;
    visibility: hidden;
    position: fixed;
    z-index: 10000;
    bottom: 20px;
    right: 20px;
    font-size: 10px;
    padding: 0 10px 10px 10px;
    border-radius: 5px;
    background: linear-gradient(to bottom right, red, orange);
    color: white;
    pointer-events: none; 
    transition: opacity 1s;	
}

#backtop-button:hover {   opacity: 1 !important; }

#backtop-button span { display: block;
  			   font-size: 30px;
}

 

The look of the Scroll To Top button from our example

If you have done everything correctly, the Scroll To Top Button should look something like this. If it doesn’t check if any CSS properties from your webiste override the button’s properties.

 

How does the code work?

The HTML <button> element has the onclick event defined to trigger the BackTop function, which is defined in the JavaScript code that follows. The button id name is also mandatory, because the JavaScript code will change the CSS properties related to the id.

A <span> element containing Unicode code for the arrowhead icon and the button text are wrapped inside the <button> tags. We use Unicode symbols here instead of images or Font Awesome icons, to keep the loading speed and weight as low as possible.

In the JavaScript <script>, firstly we define the BackTopButton variable by the button’s id name, so we can modify it’s CSS properties. Secondly, we make scrolling of the page or post trigger the ScrollOffset function using the window.onscroll event.

We define the ScrollOffset function to change specific button’s CSS properties when the page is scrolled more than 100px from the top. The function will change the button’s visibility from hidden to visible, make it 70% transparent and make the button clickable. Finally, we define the BackTop function to scroll the post or page back to the top when the Scroll To Top Button is clicked. The function also checks if we’re back below 100px from the top, and if so it reverts the CSS properties to their initial values and hides the button.

The CSS properties are pretty much self explanatory, except for the scroll-behavior property. We’re applying that property to the whole website, to get the smooth animated scroll effect when the Scroll To Top Button is clicked. The property affects the whole website, meaning that if you use any anchor links on your pages, the smooth scroll effect will apply to them too.

Since the scroll-behavior is a quite new CSS property, at the moment of writing this tutorial it’s not supported by Safari browser yet. Therefore, in Safari browser the jump to the top of the page will be immediate, without the smooth scroll animation. There are other Scroll To Top Button scripts available that use jQuery animation supported by Safari, but with the goal to keep our script as lightweight and fast as possible, we prefer to use JavaScript. Hopefully, the scroll-behavior CSS property will be supported by all browsers quite soon.

 

Customizing the Scroll To Top Button JavaScript code

There are several possibilities to customize the Scroll To Top Button code from our example. By simple modifications of specific values inside the code you can adjust the look and behavior of the button according to your needs and website style. Here’s a list of possible modifications of the code above:

The <button> element:

  • remove <span>&# 9650;<span> if you don’t want to use the icon, but text only
  • change &# 9650; inside the span to any other Unicode character
  • you can use an image or 3rd party icon (Font Awesome, etc..) instead the Unicode character, but it will create additional server requests and add weight to the script
  • edit the Back Top text according to your needs, or remove it if you wish to create an icon only Scroll To Top Button

The JavaScript<script> functions:

  • adjust the scroll offset value in pixels when the Scroll To Top Button appears (set to 100 in our example)
  • change the transparency of the button by adjusting the opacity value (set to 0.7 in our example, 1 is no transparency at all)

The CSS properties of the Scroll To Top Button:

  • remove the scroll-behavior property if you dont want to use the smooth scroll animation
  • adjust the z-index property if needed, according to your website layout
  • adjust the button position by editing the bottom and right properties
  • customize the button visual appearance, by editing the font-size, padding, border-radius, background and color properties
  • adjust the icon size by editing the #backtop-button span font-size property

 

Back To Top Button plugins for WordPress

Not comfortable or experienced enough to edit template files? The script form our example doesn’t work for you the way it should or it doesn’t meet your expectations? Don’t worry, there are still plenty of WP plugins to try out. We tested and reviewed the most popular Back To Top Button WordPress plugins to make your choice easier. Learn more about it in our Plugins review article.