Trang chủ
Scroll Top & Bottom
Save
Settings
Sign Up
Log In
Save
Settings
HTML
Copy
<!-- Nút scroll lên đầu --> <button class="scroll-btn js-scrollTopBtn">⬆️ Top</button> <!-- Nút scroll xuống cuối --> <button class="scroll-btn js-scrollBottomBtn">⬇️ Bottom</button>
CSS
Copy
body { line-height: 1.6; height: 3000px; /* để có nội dung dài cho cuộn */ padding: 20px; } /* Nút chung */ .scroll-btn { position: fixed; right: 30px; padding: 10px 15px; font-size: 16px; border: none; color: white; border-radius: 8px; cursor: pointer; z-index: 999; box-shadow: 0 4px 10px rgba(0,0,0,0.3); display: none; /* ẩn mặc định */ } /* Nút lên đầu */ .js-scrollTopBtn { bottom: 30px; background-color: #333; } /* Nút xuống cuối */ .js-scrollBottomBtn { bottom: 80px; background-color: #444; } .scroll-btn.show { display: block; }
JS
Copy
const scrollTopBtn = document.querySelector(".js-scrollTopBtn"); const scrollBottomBtn = document.querySelector(".js-scrollBottomBtn"); if (!scrollTopBtn || !scrollBottomBtn) return; // Hàm scroll về đầu function scrollToTop() { window.scrollTo({ top: 0, behavior: "smooth" }); } // Hàm scroll xuống cuối function scrollToBottom() { window.scrollTo({ top: document.body.scrollHeight, behavior: "smooth" }); } // Gán sự kiện click scrollTopBtn.addEventListener("click", scrollToTop); scrollBottomBtn.addEventListener("click", scrollToBottom); // Hiện/ẩn nút theo vị trí cuộn window.addEventListener("scroll", () => { const scrollY = window.scrollY; const windowHeight = window.innerHeight; const pageHeight = document.documentElement.scrollHeight; // Hiện nút Top nếu cuộn xuống hơn 200px if (scrollY > 200) { scrollTopBtn.classList.add("show"); } else { scrollTopBtn.classList.remove("show"); } // Hiện nút Bottom nếu chưa tới cuối if (scrollY + windowHeight < pageHeight - 200) { scrollBottomBtn.classList.add("show"); } else { scrollBottomBtn.classList.remove("show"); } });