Unlocking Scroll Magic: Enhance Web Experience with Dynamic Scroll In Javascript
We often see features like infinite scroll in many applications. This is a feature which is very relevant to this day. Also there can be situations where we need to add functionality based on our document’s scroll position. For example you might want to do something or trigger a function based on the scroll height of the document. Here is how we can do that efficiently.
In javascript, we can use window.scrollY properties to get the document’s scroll position:
window.addEventListener('scroll', function() {
if(window.scrollY > 590){
// do something
}
})
Here, this function will trigger each time user scrolls the document. And it will execute the conditional block, when the scroll height is over 590 pixels.
For example, you might want to show a hidden item based on scroll position. So you can show it when the scroll height (590 pixel) is exceeded, Here is an example:
window.addEventListener('scroll', function() {
if(window.scrollY > 590){
document.querySelector('.toolbar').classList.add('d-block')
}else{
document.querySelector('.toolbar').classList.add('d-none')
}
})
For infinite scrolling, we can use this way and call api to fetch data from backend.
I hope you have found this tip helpful. Feel free to have your comments down here or give a love to this article.
Have a great day.
Comments