JavaScript Scrolling: Scroll Events and Methods
Scrolling is a common action in web development, and JavaScript provides multiple ways to control, detect, and manipulate scrolling behavior.
🔹 1. Detect Scroll Events (scroll
)
The scroll
event fires whenever the user scrolls a page or an element.
✔ Example: Detect Page Scroll
🛠 Effect: Logs a message whenever the user scrolls.
🔹 2. Get Scroll Position
We can retrieve the current scroll position of the page using window.scrollY
and window.scrollX
.
✔ Example: Get Vertical and Horizontal Scroll Position
🔹 window.scrollY
→ Returns vertical scroll position.
🔹 window.scrollX
→ Returns horizontal scroll position.
🔹 3. Scroll to a Specific Position
We can programmatically scroll the page using scrollTo()
.
✔ Example: Scroll to the Top
✔ Example: Scroll to a Specific Position Smoothly
🔹 behavior: "smooth"
→ Enables smooth scrolling.
🔹 4. Scroll by a Certain Amount
We can scroll relative to the current position using scrollBy()
.
✔ Example: Scroll Down by 100px
✔ Example: Scroll Left by 50px
🔹 5. Scroll an Element (Not the Whole Page)
We can scroll inside a specific element using .scrollTop
and .scrollLeft
.
✔ Example: Get Scroll Position of an Element
✔ Example: Scroll to Bottom of an Element
✔ Example: Scroll an Element Smoothly
✅ HTML Example with Scrollable Div
🔹 scrollHeight
→ The total scrollable height of an element.
🔹 scrollTop
→ The current vertical scroll position.
🔹 6. Smooth Scrolling with scrollIntoView()
We can scroll an element into view automatically.
✔ Example: Scroll an Element into View
🔹 behavior: "smooth"
→ Enables smooth scrolling.
🔹 block: "center"
→ Positions the element in the center of the viewport.
✅ HTML Example
🔹 7. Prevent Page Scrolling
To disable scrolling on the page:
To enable scrolling again:
🎯 Conclusion
✅ scrollY
, scrollX
→ Get current scroll position.
✅ scrollTo()
→ Scroll to a fixed position.
✅ scrollBy()
→ Scroll relative to current position.
✅ scrollIntoView()
→ Bring an element into view.
✅ .scrollTop
, .scrollLeft
→ Scroll inside an element.
✅ overflow: hidden
→ Disable scrolling.
🚀 Now you can control scrolling like a pro!