I know how to make this scroll effect to an element having some class/id
. What I don’t get is to make the scroll
stop at 20px
above this element. I’ve seen examples that do it with document.getElementById()
. like this:
function scrollToJustAbove(element, margin=20) { let dims = element.getBoundingClientRect(); window.scrollTo(window.scrollX, dims.top - margin); }
But, in my case I also need a smooth transition
that is what I want (like my link in plnrk). How can I do it?
this is my code:
https://plnkr.co/edit/3NX4FK5QrjiTwYgK5vwj?p=preview
setTimeout(() => { const classElement = document.getElementsByClassName("myclass"); if(classElement.length > 0){ classElement[0].scrollIntoView({ block: 'start', behavior: 'smooth'}); } }, 100);
Advertisement
Answer
Use window.scrollTo() instead of
element.scrollIntoView()
The scrollTo method is Polymorphic. Apart from the params you already know, it instead also takes just an object (dictionary) in which you can specify the scroll behavior, like so:
<script> function scrollToJustAbove(element, margin=20) { let dims = element.getBoundingClientRect(); window.scrollTo({ top: dims.top - margin, behavior: 'smooth' }); } setTimeout(() => { const classElement = document.getElementsByClassName("myclass"); if(classElement.length > 0){ scrollToJustAbove(classElement[0]); } }, 100); </script>
Working Example: https://plnkr.co/edit/UevhAN4NmTCdw65dzuPe?p=preview