scroll() method: Define Any Action When Page is Scrolled in Jquery.

Date Published: 11/05/2020 Published By: JaiSchool

The scroll() event in Jquery executes when the page is scrolled. In its parameter, we define an anonymous function to be executed while scrolling.

Simple example~

Use this code if you want to define any action when document is scrolling.

<!DOCTYPE html>
<html>
<head>
  <title>Jquery scroll()</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body style="height:1000px;">

<h1 id="position" align="center">Scroll page to hide me</h1>
<button id="btn">Show text</button>

<script>

$(document).ready(function(){
    $(document).scroll(function(){
    $("#position").css({display:"none"});
});
    $("#btn").click(function(){$("#position").css("display","block")});
});

</script>

</body>
</html>

When any element is scrolled in the document

When any element on the document has scrollbar and you want to define action when scrolled any of them. Then use * selector to select all the elements. or you can also select a particular element by id or class or tag. See below example

<!DOCTYPE html>
<html>
<head>
  <title>Jquery scroll()</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>

<h1 id="position" align="center">Scroll page to hide me</h1>

<center><div style="width:150px;height:150px;border:1px solid black;overflow:scroll;">
  HTML stands for hypertext markup language. As its name suggests that HTML is a markup language which means it is used to markup content on webpages by tags which tells a web browser how to structure content to display on web pages. HTML was invented by Team Berners Lee.
</div></center>

<button id="btn">Show text</button>

<script>

$(document).ready(function(){
    $("*").scroll(function(){
    $("#position").css({display:"none"});
});
    $("#btn").click(function(){$("#position").css("display","block")});
});

</script>

</body>
</html>

Publish A Comment

Leave a Reply

Your email address will not be published.