How to determine the direction of a jQuery scroll event?
Last Updated :
16 Sep, 2022
The scrollTop() method in jQuery is used to set or return the vertical scrollbar position for the selected elements. With the help of this method, we can find the mouse scroll direction. Syntax:
$(selector).scrollTop(position)
Parameters: This method accepts single parameter position which is optional. It is used to specify the vertical scrollbar position in pixels. Return Value: It returns the vertical position of the scrollbar of selected element. Example:
html
<!DOCTYPE html>
< html >
< head >
< title >
Determine the direction of scroll event
</ title >
< script src=
</ script >
< style >
html, body {
height: 300%
}
div {
position: fixed;
padding-left: 10px;
padding-top: 30px;
height: 10%;
width: 35%;
background: lightgrey;
font-weight: bold;
border: 2px solid green;
}
</ style >
</ head >
< body >
< div ></ div >
< script >
var position = $(window).scrollTop();
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll > position) {
console.log('scrollDown');
$('div').text('Scrolling Down Scripts');
} else {
console.log('scrollUp');
$('div').text('Scrolling Up Scripts');
}
position = scroll;
});
</ script >
</ body >
</ html >
|
Output:
- Scrolling in up direction:
- Scrolling in down direction:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...