What is On Scroll Event in JavaScript ?
What is On Scroll Event in JavaScript?
The basic idea of the On Scroll event lies with the functioning of different tasks, such as animation, responsiveness, hiding or displaying, and many more with respect to the scrolling of the page.
This depends on an event listener which will have an event of the scroll, then a function to collect the data of scrolled page with the help of page offset and finally the changes to be made which can be the altering style of some division, displaying of some element and also hiding of some element.
There are many syntaxes to make this in action
In HTML:
<element onscroll="myScript">
In JavaScript:
object.addEventListener("scroll", myScript);
In JavaScript using event listener:
object.addEventListener("scroll", myScript);
Example:
window.addEventListener('scroll', function() {
document.getElementById('showScroll').innerHTML = window.pageYOffset + 'px';
});
In the above code, it is shown that an event listener is fired on the window with a scroll event that has a function.
This function is linking itself with the id of show scroll and this id is receiving values equivalent to the pixels being scroll in the Y-axis of the page.
Scroll Offsets
The window has two properties related to the scroll event. These two properties are
- scrollX
- scrollY
They return the precise value of the page being scrolled, so often the values are in decimals.
NOTE: The pageXOffset and pageYOffset are aliases of the scrollX and scrollY properties.
Scroll event on Navbar:
- Create a navbar with HTML Code with an id tag to it.
E.g.
<div class="navbar">
</div>
- Give it some height with CSS and a background color too.
E.g.
.navbar{
background-color: red;
width: 100%;
height: 50px;
display: block;
position: fixed;
}
- Define the body of height greater than the viewport
- Now write a function to change the height of the navbar on scroll
function navbar(){
const nav = document.querySelector('.navbar');
var pos = window.pageYOffset;
console.log(pos)
if (pos>80){
nav.style.height = "70px"
}
}
window.addEventListener('scroll', navbar);
The end results will be like: