generate functionMon, 26 Dec 2022

when clicking an element, center its parent vertical scroll to the element

function scrollToElement(element) { const elementTop = element.getBoundingClientRect().top; const elementBottom = element.getBoundingClientRect().bottom; const elementHeight = elementTop - elementBottom; const parent = element.parentNode; const scrollHeight = parent.scrollHeight - parent.getBoundingClientRect().height; const center = Math.min(scrollHeight, Math.max(0, elementHeight - parent.getBoundingClientRect().height / 2)); parent.scrollTo({ top: center, behavior: 'smooth', }); }

Javascript
Generate More

Questions about programming?Chat with your personal AI assistant