JAVASCRIPT
Programmatically Scrolling to an Element or Page Position
Implement smooth scrolling in JavaScript to bring specific elements into view or navigate to precise pixel positions on a webpage.
const targetElement = document.getElementById('targetSection');
// Scroll to an element with smooth behavior
targetElement.scrollIntoView({
behavior: 'smooth',
block: 'start' // 'start', 'center', 'end', or 'nearest'
});
// Alternatively, scroll to a specific pixel position
// window.scrollTo({
// top: 500, // 500 pixels from the top of the document
// left: 0,
// behavior: 'smooth'
// });
How it works: This snippet shows two ways to control page scrolling programmatically. `scrollIntoView()` is used to scroll the viewport to make a specific element visible, with options for smooth animation and alignment. `window.scrollTo()` offers more granular control, allowing scrolling to exact pixel coordinates on the page, also with optional smooth behavior.