Home >>jQuery Tutorial >jQuery scroll() Method

jQuery scroll() Method

jQuery scroll() Method

jQuery scroll() method in jQuery is used to add a function or triggers the scroll event to run when a scroll event occurs in the specified element.

Syntax:

Trigger the scroll event for the selected elements:

$(selector).scroll()

Attach a function to the scroll event:

$(selector).scroll(function)

Parameter Values

Parameter Description
function It is an optional parameter and used to specifies the function to run when the scroll event is triggered
Here is an Example of jQuery scroll() Method:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
var x = 0;
$(document).ready(function(){
$(".box").scroll(function(){
$(".num").text( x+= 1);
});
});
</script>
</head>
<body>
<p>scroll the content in the div</p>
<div class="box" style="border:1px solid black;width:180px;height:180px;overflow:scroll;">
There once was a little boy who had a very bad temper. His father decided to hand him a bag of nails and said that every time the boy lost his temper, he had to hammer a nail into the fence.<br><br>
On the first day, the boy hammered 37 nails into that fence.
</div>
<p>Scrolled <span class="num">0</span> times.</p>
</body>
</html>

Output:

scroll the content in the div

There once was a little boy who had a very bad temper. His father decided to hand him a bag of nails and said that every time the boy lost his temper, he had to hammer a nail into the fence.

On the first day, the boy hammered 37 nails into that fence.

Scrolled 0 times.