Basic example
Button to return to the top of the page allows the user to quickly return to the top of the page without making too much effort. This can be very useful when the page has a lot of content.
Use the code below to create button that scrolls back to the beginning of the page.
<!-- Back to top button --> <button type="button" data-twe-ripple-init data-twe-ripple-color="light" class="!fixed bottom-5 end-5 hidden rounded-full bg-red-600 p-3 text-xs font-medium uppercase leading-tight text-white shadow-md transition duration-150 ease-in-out hover:bg-red-700 hover:shadow-lg focus:bg-red-700 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-red-800 active:shadow-lg" id="btn-back-to-top"> <span class="[&>svg]:w-4"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="3" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" d="M4.5 10.5 12 3m0 0 7.5 7.5M12 3v18" /> </svg> </span> </button> <!-- Explanation --> <div class="container mx-auto mt-4 text-center dark:text-white" style="height: 2000px"> <p class="mb-4"> Start scrolling the page and a strong <strong>"Back to top" button </strong> will appear in the <strong>bottom right corner</strong> of the screen. </p> <p>Click this button and you will be taken to the top of the page.</p> </div>
import { Ripple, initTWE, } from "tw-elements"; initTWE({ Ripple }); // Get the button const mybutton = document.getElementById("btn-back-to-top"); // When the user scrolls down 20px from the top of the document, show the button const scrollFunction = () => { if ( document.body.scrollTop > 20 || document.documentElement.scrollTop > 20 ) { mybutton.classList.remove("hidden"); } else { mybutton.classList.add("hidden"); } }; const backToTop = () => { window.scrollTo({ top: 0, behavior: "smooth" }); }; // When the user clicks on the button, scroll to the top of the document mybutton.addEventListener("click", backToTop); window.addEventListener("scroll", scrollFunction);
// Get the button const mybutton = document.getElementById("btn-back-to-top"); // When the user scrolls down 20px from the top of the document, show the button const scrollFunction = () => { if ( document.body.scrollTop > 20 || document.documentElement.scrollTop > 20 ) { mybutton.classList.remove("hidden"); } else { mybutton.classList.add("hidden"); } }; const backToTop = () => { window.scrollTo({ top: 0, behavior: "smooth" }); }; // When the user clicks on the button, scroll to the top of the document mybutton.addEventListener("click", backToTop); window.addEventListener("scroll", scrollFunction);
Related resources
Tutorials:
Extended Docs:
colors hover effects icons footer pagination buttons testimonials timeline ripple breakpoints color picker colors dark theme display flex float right hero icons icons position spacing sticky footer visibility hidden z index