Property window.scrollY คืนค่าจำนวนพิกเซลที่เอกสารถูก Scroll แนวตั้ง (Vertical) จากมุมซ้ายบนของหน้าต่าง Browser เทียบเท่า window.pageYOffset
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<head>
<style>
div {
background-color: yellow;
height: 1500px;
width: 1500px;
}
</style>
</head>
<body>
<script>
function scrollFunc() {
window.scrollBy(200, 200);
alert("Vertical: " + window.scrollY);
}
</script>
<button onclick="scrollFunc()" style="position:fixed;">Scroll</button>
<br><br><br>
<div></div>
</body>
</html>
คำอธิบาย
window.scrollBy(200, 200)— Scroll ลง 200px และขวา 200pxwindow.scrollY— อ่านตำแหน่ง Scroll แนวตั้งปัจจุบัน (Read-only)window.pageYOffset— Alias เดิม ทำงานเหมือนกันทุก Browser สมัยใหม่
Properties ที่เกี่ยวข้อง
| Property | ความหมาย | Alias |
|---|---|---|
scrollX | Horizontal Scroll (px) | pageXOffset |
scrollY | Vertical Scroll (px) | pageYOffset |
scrollTo(x, y) | Scroll ไปตำแหน่งสัมบูรณ์ | - |
scrollBy(x, y) | Scroll แบบ Relative | - |
การใช้งานจริง
- Infinite Scroll / Lazy Load: เช็ค
scrollY + innerHeight >= document.body.scrollHeight - Back to Top Button: แสดงเมื่อ
scrollY > 300 - Reading Progress Bar:
(scrollY / (scrollHeight - innerHeight)) * 100 - Sticky Sidebar: คำนวณตำแหน่ง Fixed จาก Scroll Offset