Expand my Community achievements bar.

SOLVED

go-to-top component and example

Avatar

Level 4

Hello,

 

In a project I'm working on, I have a requirement for a component that has a go-to-top icon (or text) that appears on every page.

 

I'm wondering as to how this can be implemented, and if anyone has an example that has already been implemented, can you share it with me?

 

Thank you in advance.

 

1 Accepted Solution

Avatar

Correct answer by
Community Advisor
4 Replies

Avatar

Community Advisor

@keehwan1 The JS , CSS code should look like something in the article.

https://www.w3schools.com/howto/howto_js_scroll_to_top.asp

 

For this component to show up on all pages, just add this component in your base/root page template so that all pages contain this component.

Avatar

Community Advisor

Hi @keehwan1 
To implement a go-to-top component that appears on every page, you can use a combination of HTML, CSS, and JavaScript

  1. Add the following HTML code to your page template or layout file, where you want the go-to-top component to appear
    <div id="go-to-top">
      <a href="#" title="Go to top"><i class="fa fa-chevron-up"></i></a>
    </div>
    ​

    This creates a div element with an id of go-to-top, which contains an anchor link with a font-awesome icon for the up arrow.

    1. Add the following CSS code to your stylesheet
      #go-to-top {
        position: fixed;
        bottom: 20px;
        right: 20px;
        z-index: 9999;
      }
      
      #go-to-top a {
        display: block;
        width: 40px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        background-color: `#333`;
        color: `#fff`;
        border-radius: 50%;
        transition: background-color 0.3s ease-in-out;
      }
      
      #go-to-top a:hover {
        background-color: `#555`;
      }
      ​

    This styles the go-to-top component with a fixed position at the bottom right of the screen, and adds some basic styling to the link.

    1. Add the following JavaScript code to your page template or layout file, just before the closing </body> tag
      var goToTop = document.getElementById('go-to-top');
      
      window.onscroll = function() {
        if (window.pageYOffset > 100) {
          goToTop.style.display = 'block';
        } else {
          goToTop.style.display = 'none';
        }
      };
      
      goToTop.onclick = function() {
        window.scrollTo(0, 0);
      };
      ​
    This adds a scroll event listener to the window object, which shows or hides the go-to-top component based on the current scroll position. It also adds a click event listener to the go-to-top link, which scrolls the window back to the top when clicked.

 



Avatar

Correct answer by
Community Advisor

Avatar

Community Advisor

@keehwan1 

 

I hope the suggestions helped you.

Requesting you to please mark the answer 'correct' that worked best for you.


Aanchal Sikka