jQuery scroll()

Filed Under: jQuery

jQuery scroll() function triggers when the element is scrolled. This method attaches a handler, which executes when the scroll event is fired. A scroll event fires for all elements which are scrollable and it also fires for window objects.

jQuery scroll()

The syntax for using jQuery scroll() function is:

  • scroll()

This signature is used without any arguments. This method is a shortcut for .trigger( "scroll" ).

  • scroll(handler)

The handler is a function, which is executed when the element gets scrolled. This method is a shortcut for .on( "scroll", handler ).

jQuery scroll example

Following example demonstrates jQuery scroll() function usage.


<!DOCTYPE html>
<html>
<head>
<title>jQuery Scroll</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<style>
p {
color: green;
}
.divScroll{
border:1px solid black;
width:100px;
height:200px;
overflow:scroll;
}
</style>
<script>
var x=0;
$(document).ready(function(){
  $("div").scroll(function(){
    $("span").text(x++);
  });
});
</script>
</head>
<body>

<p><b>Scroll Event Demo</p>
<div class="divScroll">Paragraph one Paragraph two Paragraph three Paragraph four Paragraph five Paragraph  six Paragraph seven</div>
<p>Scroll event triggered <b><span>0</span></b> times.</p>

</body>
</html>

In this example, you can see that the scroll() method is triggered when you scroll in the <div> element. The handler attached to the scroll() method executes with each scroll event displays the count below the <div> element.

jQuery scroll demo

You can try it yourself by scrolling in the below div section.

Comments

  1. david says:

    ye got this from wc3 site
    very exciting

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages