← Snippets - Script

Fade In/Out Back to Top Button

What It Does

Shows/hides back to top icon depending on where you are scrolling on the page.

How to Implement

This is a very basic example - you’ll most likely need to expand its style to match your site

HTML

Only works when BTT is position fixed. In this example, the button is only shown/hidden on xl and above. If you wanted to make it always behave like this, change position-absolute to position-fixed and get rid of the extra -xl classes.

<div id="back-to-top" class="position-absolute position-xl-fixed">
   <a href="#">
      <span class="icon icon-arrow-up" aria-hidden="true"></span>
      <span class="sr-only">Go to the top of the page</span>
   </a>
</div>

JavaScript

When scroll position is 10% of the distance from the top to the footer. Change .1 to make it appear sooner or later.

if ($(window).scrollTop() > $('#footer').offset().top * .1){
  $('#back-to-top').addClass('on-screen');
} else {
  $('#back-to-top').removeClass('on-screen');
}

SCSS

The pointer-events style prevents the icon from getting clicked while it’s hidden.

#back-to-top{
  bottom: 30px;
  left: 0;
  opacity: 0;
  transition: all .25s ease;
  pointer-events: none;
  z-index: 100;

  &.on-screen{
    opacity: 1;
    
    a{
      pointer-events: all;
    }
  }
}

Reference Sites


Tags: bs4, bootstrap 4, javascript, html, scss, css, style, show, hide