Home »
jQuery »
jQuery Examples
How can I determine the direction of a jQuery scroll event?
In this tutorial, we'll learn how to get the direction of a jQuery Scroll Event?
Submitted by Pratishtha Saxena, on July 22, 2022
When a webpage is created, we can determine the value of the scroll event using jQuery's scrollTop() and scrollLeft() Methods.
These two methods will help us to get the current position of the scroll bar on the webpage.
jQuery scrollTop() Method
It is an inbuilt jQuery method. It is used to get the value of the position of the vertical scrollbar for the selected elements. We can select any DOM element and get its position relative to the scrollbar.
Syntax:
$(selector).scrollTop(position);
Apart from returning the value of the scrollbar, it can also be used to set the scrollbar value for the element. The position here is mentioned when we want to set the value of the selected element on the webpage.
jQuery scrollLeft() Method
It is same as scrollTop() method. The difference is that scrollLeft() will return or set the value of the horizontal scrollbar of the webpage. The syntax and working is same as the above.
Syntax:
$(selector).scrollLeft(position);
Example:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div class="box"></div>
</body>
</html>
CSS:
<style>
html, body {
height: 150%;
width: 150%;
}
.box {
position: fixed;
margin: 20px;
padding-left: 10px;
padding-top: 10px;
height: 15%;
width: 15%;
background: #e0edc2;
font-weight: bold;
text-align: center;
}
</style>
jQuery:
<script>
$(document).ready(function(){
$(window).scroll(function(){
$('.box').html('');
$('.box').append("Top: "+ $(window).scrollTop());
$('.box').append("<br>Left: "+ $(window).scrollLeft());
console.log($(window).scrollTop());
});
});
</script>
Output: