Exercise 10: Scroll Element into View

Problem Statement

Function `scrollIntoView(el, options)` banao jo element ko viewport me scroll kare. Example: scrollIntoView(buttonEl, {behavior: "smooth"})

Sample Output:

scrollIntoView(buttonEl, {behavior: "smooth"})
// Smoothly scrolls element into view

Solution

const scrollIntoView = (el, options = {}) => el?.scrollIntoView({behavior: "smooth", block: "center", ...options});

Explanation

Overall Goal:

  • Element ko viewport me scroll karna.

Real world:

  • Navigation: scroll to section.
  • Focus: scroll to focused element.