jQuery scroll() scroll and check offset

Description

jQuery scroll() scroll and check offset

View in separate window

<!DOCTYPE html>
<html>
<head>
<script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>//ww w  .ja  v  a  2 s. c  o  m
<script>
$(document).ready(function() {
  $(window).scroll(function() {
    if ($(document).scrollTop() > 50) {
      $("p").addClass("test");
    } else {
      $("p").removeClass("test");
    }
  });
});
</script>
<style>
.test {
  background-color: red;
}
</style>
</head>
<body style="height:1550px;">

<p>Scroll down this page.</p>

<p style="position:fixed;">
When you have scrolled 50 pixels from the top, 
add the class "test"
to the paragraph. Scroll up again to remove 
the class.</p>

</body>
</html>



PreviousNext

Related