jQuery scroll() Method

jQuery | scroll() Method: Learn about the jQuery scroll() Method with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on October 30, 2022

scroll() Method

Events in jQuery are the actions that the user performs on the web page. It can be anything – related to mouse clicks, keyboard presses, etc. Using jQuery, we can control these events in the order we want and can also attach some custom functions to it if needed. That means, we can use predefined event methods for the actions and also define a function that gets fired when the event method is triggered. Overall, this makes the website more dynamic on the user's end. Let's learn about the scroll() method here.

The scroll() method is a built-in jQuery method. This method gets triggered whenever the selected element is scrolled. Even the scroll is just very minute, but this method detects that too, hence the function attached to it is executed each and every time.

scroll() Method Syntax

$('selector').scroll(function);

It takes one optional parameter – function. It gets fired if the method is called. This method returns the output given by the respective function. In the example given below, each time the page is scrolled down or scrolled up, the method gets called and hence, the given expression gets added.

jQuery scroll() Method Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
    <style>
      html, body{
      height: 300%;
      }
    </style>
  </head>
  
  <body>
    <h2>jQuery Event - Scroll</h2>
    <p>Scroll down the page to see the results.</p>
    <hr>
    <h4 style="color:darkblue">Welcome to Include Help !</h4>
    <p>This is a jQuery Tutorial for Event Methods.</p>
    <h4 style="color:darkblue">Thanks for visiting !</h4>
    <img style="height: 200px;" id="myImg" src="https://media.istockphoto.com/photos/mountain-landscape-picture-id517188688?k=20&m=517188688&s=612x612&w=0&h=i38qBm2P-6V4vZVEaMy_TaTEaoCMkYhvLCysE7yJQ5Q=">
    <hr>
    <h3></h3>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $(window).scroll(function(){
            $('h3').append("!_");
        });
    });
  </script>
</html>

Output:

Example 1: jQuery scroll() Method



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.