Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การใช้งาน Event onscroll ใน JavaScript

Event onscroll (หรือ scroll) ทริกเกอร์เมื่อ Scrollbar ถูกเลื่อน ภายใน Element ที่มี Overflow (รวม Window)

ตัวอย่างโค้ด

<!DOCTYPE html>
<html>
  <head>
    <style>
      div {
        border: 2px solid blue;
        width: 300px;
        height: 100px;
        overflow: scroll;
      }
    </style>
  </head>
  <body>
    <div id="content">
      This is demo text. This is demo text.This is demo text.This is demo text.
      This is demo text.This is demo text.This is demo text.This is demo text.
      This is demo text.This is demo text.This is demo text.
      This is demo text.This is demo text.This is demo text.
      This is demo text.This is demo text.This is demo text.
    </div>
    <p id="myScroll"></p>
    <script>
      document.getElementById("content").onscroll = function() { myFunction() };
      function myFunction() {
        document.getElementById("myScroll").innerHTML = "Scroll successful!";
      }
    </script>
  </body>
</html>

คำอธิบาย

  • Element ต้องมี overflow: scroll หรือ auto และเนื้อหายาวกว่าพื้นที่
  • element.onscroll หรือ element.addEventListener('scroll', handler)
  • Window Scroll: window.addEventListener('scroll', handler)

⚠️ Performance Warning

Scroll Event ยิง มากมาย (High Frequency) ต้อง Optimize เสมอ:

  • Throttle (requestAnimationFrame): รันสูงสุด 60fps
  • Passive Listener: addEventListener('scroll', handler, {passive: true}) ไม่ Block Scroll
  • Intersection Observer: แทน Scroll สำหรับ Detect Visibility (Lazy Load, Animation Trigger)

ตัวอย่าง Throttle ด้วย rAF

let ticking = false;
window.addEventListener('scroll', () => {
  if (!ticking) {
    window.requestAnimationFrame(() => {
      // ทำงานที่นี่: update UI, check position
      console.log('Scroll Y:', window.scrollY);
      ticking = false;
    });
    ticking = true;
  }
}, {passive: true});

Intersection Observer (แทน Scroll สำหรับ Visibility)

const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      console.log('Element visible:', entry.target);
    }
  });
}, {threshold: 0.5});
observer.observe(document.querySelector('.target'));