Ví dụ jQuery
<html>
<body>
<script>
$("a").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false; // Ngăn default anchor behavior
});
</script>
<h3>TOP OF PAGE</h3>
<br> ... nội dung dài ...
<h3>BOTTOM OF PAGE</h3>
<a href="#">Scroll up</a>
</body>
</html>
Vanilla JavaScript (Modern - không cần jQuery)
// 1. Smooth scroll to top
document.querySelector('#scrollTopBtn').addEventListener('click', () => {
window.scrollTo({ top: 0, behavior: 'smooth' });
});
// 2. Instant scroll
window.scrollTo(0, 0);
// hoặc
document.documentElement.scrollTop = 0;
// 3. Scroll element cụ thể
element.scrollTo({ top: 0, behavior: 'smooth' });
// 4. ScrollIntoView (cho element)
document.getElementById('topSection').scrollIntoView({ behavior: 'smooth' });
CSS Scroll Behavior (No JS needed!)
html {
scroll-behavior: smooth;
}
/* Anchor link tự smooth scroll */
Back to Top
Content...
Scroll to Top Button Pattern (UX)
// Show/hide button based on scroll position
const btn = document.getElementById('scrollTopBtn');
window.addEventListener('scroll', () => {
if (window.scrollY > 300) {
btn.classList.add('visible');
} else {
btn.classList.remove('visible');
}
});
btn.addEventListener('click', () => {
window.scrollTo({ top: 0, behavior: 'smooth' });
});
So sánh
| Phương pháp | Smooth? | Dependency | Browser Support |
window.scrollTo({behavior:'smooth'}) | ✅ | None | Modern (IE không hỗ trợ smooth) |
scroll-behavior: smooth CSS | ✅ | None | Modern (IE không) |
jQuery .animate() | ✅ | jQuery | All (polyfill) |
scrollTop = 0❌ Instant | None | All |