เรียนรู้ smooth scroll ผู้ใช้ไปด้านล่างหน้ายาว ด้วย JS และ CSS นิดหน่อย
ใช้ CSS property scroll-behavior และ JS method scrollIntoView()
ต้องมี:
- หน้ายาวพอให้มี y-axis scrollbar
- Anchor element ที่บนสุดมี id
- Element ใดๆ ที่ล่างสุดมี id
scroll-behaviorCSS propertyscrollIntoView()JS property
HTML Layout Example
<main>
<p><a id="scroll-to-bottom">Scroll to bottom</a></p>
<p>....</p> (หลายบรรทัด)
<p id="page-bottom">You have reached the bottom of this page!!</p>
</main>
CSS
html {
scroll-behavior: smooth;
}
main {
max-width: 700px;
margin: 3rem auto;
padding: 0 1rem;
}
#scroll-to-bottom {
font-weight: bold;
color: green;
}
Scroll magic มาจาก scroll-behavior: smooth; ส่วนที่เหลือ cosmetic
JavaScript
let scrollToBottom = document.querySelector("#scroll-to-bottom");
let pageBottom = document.querySelector("#page-bottom");
scrollToBottom.addEventListener("click", function() {
pageBottom.scrollIntoView();
});
JS ทำงานอย่างไร
- Declare 2 variables reference
scroll-to-bottomและpage-bottom - Attach event listener listen
clickevents - ใน function เรียก
scrollIntoView()บน pageBottom element
คลิก scroll to bottom → scroll ไป id page-bottom
Note: ลบ scroll-behavior: smooth; scroll ยังทำงานแต่ abrupt
Pure vanilla JS smooth scroll ได้แต่ code ยาวกว่ามาก
ประโยชน์ในชีวิตจริง
Use case: ให้ visitor scroll เร็วไป summary ของเนื้อหายาวที่ไม่อ่านหมดทัน
Browser Compatibility
scroll-behavior ไม่รองรับ IE และ Safari ต้องใช้ pure JS solution แทน