Thoughts On Web Design

Add A Scroll To Top Button

Add A Scroll To Top Button

In this post we are adding a button that will scroll users to the top of the page when clicked using JavaScript and some CSS.

Scroll To Top Button

Add The <A> Tag For The Button

We are adding the <a> tag for the button to our html. Please note that we are using Font Awesome for the up arrow.

1. Adjust as needed and add the following code to website's html right before the </body>.

<a href="#" id="site-scroll-top"><span class="fa fa-chevron-up"> </span></a>

Add JavaScript For Functionality

We are adding the JavaScript that will make the browser scroll to the top of the page when the button is clicked. The scroll to top button shows up when the user has scrolled the top of the page to the website's menu which has the id "menu". Please change the id "menu" to whatever id scroll point on your page that you want the button to appear. It toggles the visibility of the button by adding or removing a class called visible when it reaches that point.

1. Adjust as needed and add the following code to your website's .js file.

window.addEventListener('scroll', scrollUpButton);
var navbar = document.getElementById("menu");
var upLink = document.getElementById("site-scroll-top");
var sticky = navbar.offsetTop;
function scrollUpButton() {
if (window.scrollY >= sticky) {
upLink.classList.add("visible")
} else {
upLink.classList.remove("visible");
}
}

Add CSS For Looks

We are adding the CSS that will style the button. The button styled as below is a light grey circle with a white border and a medium grey up arrow. When you hover over the button it turns blue with a white arrow. It is set to show up in the bottom right corner of the browser window.

1. Adjust as needed and add the following code to your website's .css file.

#site-scroll-top {
visibility:hidden;
opacity:0;
position:fixed;
right:2.5rem;
bottom:5rem;
color:#898989;
height:2.5625rem;
line-height:2.1875rem;
width:2.5625rem;
font-size:1.231em;
border-radius:50%;
background:#f7f7f7;
border:3px solid #fff;
text-align:center;
z-index:999;
transition:all 0.3s linear;
}

#site-scroll-top:hover, #site-scroll-top:active, #site-scroll-top:focus {
text-decoration:none;
color:#fff;
background-color:#71C9F1;
border-color:#71C9F1;
}

#site-scroll-top.visible{
visibility:visible;
display:block;
opacity:1.0;
}

THANKS FOR READING
Thank you for reading Add A Scroll To Top Button. I hope you enjoyed it. You can give me feedback, say hi or yell at me on twitter.com/beuinteractive.


Apr 29, 2024 Filed under WordPress

Reading

The Maltese Falcon

Life and Death in The Andes

Ender's Game

War and Peace

Dune

Brewing Up A Business

Latest Tweets


Follow Us On Twitter