Use scrollTo() and scroll events for scroll control
// Scroll to top
window.scrollTo({ top: 0, behavior: 'smooth' });
// Scroll element into view
element.scrollIntoView({ behavior: 'smooth' });// Smooth scroll to section
function scrollToSection(selector) {
const element = document.querySelector(selector);
element.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
}
// Detect scroll direction
let lastScroll = 0;
window.addEventListener('scroll', () => {
const currentScroll = window.pageYOffset;
if (currentScroll > lastScroll) {
console.log('Scrolling down');
} else {
console.log('Scrolling up');
}
lastScroll = currentScroll;
});
// Check if element is in viewport
function isInViewport(element) {
const rect = element.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.bottom <= window.innerHeight
);
}window.scrollTo({
top: document.body.scrollHeight,
behavior: 'smooth'
});let timeout;
window.addEventListener('scroll', () => {
clearTimeout(timeout);
timeout = setTimeout(() => {
console.log('Scroll ended');
}, 150);
});Avoid blocking scroll events
// DON'T DO THIS - causes performance issues
window.addEventListener('scroll', () => {
// Heavy computation without debouncing
performExpensiveOperation();
});✓ Works in all modern browsers (smooth behavior: Chrome 61+)