go-to-top component and example | Community
Skip to main content
March 28, 2024
Solved

go-to-top component and example

  • March 28, 2024
  • 4 replies
  • 1237 views

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.

 

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.

4 replies

Harwinder-singh
Community Advisor
Community Advisor
March 28, 2024

@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.

Raja_Reddy
Community Advisor
Community Advisor
March 28, 2024

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.

 

aanchal-sikka
Community Advisor
Community Advisor
March 31, 2024

@keehwan1 

 

I hope the suggestions helped you.

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

Aanchal Sikka