// the oldler way
function heroBtnScroll() {
const featuresEl = document.querySelector('#section--1'); // target element
const featuresElPosition = featuresEl.getBoundingClientRect(); // element positioned
console.log(featuresElPosition);
const { top, left } = featuresElPosition; //destructure to get positions from the getBoundingClientRect()
window.scrollTo({
left: left,
top: top + window.scrollY,
behavior: 'smooth',
});
}
const heroBtn = document.querySelector('.btn--scroll-to');
if (heroBtn) {
heroBtn.addEventListener('click', heroBtnScroll);
}
//the newer way using scrollIntoView
function heroBtnScroll() {
const featuresEl = document.querySelector('#section--1');
featuresEl.scrollIntoView({ behavior: 'smooth' });
}
const heroBtn = document.querySelector('.btn--scroll-to');
if (heroBtn) {
heroBtn.addEventListener('click', heroBtnScroll);
}
// testing scrolling behaviours with the document and the viewport in the console
window.addEventListener('scroll', () => {
console.log('Viewport height:', document.documentElement.clientHeight);
console.log('Vertical scroll position:', window.scrollY);
});
Comments