Home >Web Front-end >CSS Tutorial >How to Show and Hide a Div Based on Scroll Position?

How to Show and Hide a Div Based on Scroll Position?

Susan Sarandon
Susan SarandonOriginal
2024-12-13 00:42:09806browse

How to Show and Hide a Div Based on Scroll Position?

Show Hidden Div After Scrolling 800px from Top

Scenario:

You want to reveal a hidden div after the user scrolls down the page by 800 pixels. Furthermore, when the user scrolls up and the height is less than 800px, the div should disappear.

HTML Structure:

<div class="bottomMenu">
  <!-- Content -->
</div>

CSS:

.bottomMenu {
    width: 100%;
    height: 60px;
    border-top: 1px solid #000;
    position: fixed;
    bottom: 0px;
    z-index: 100;
    opacity: 0;
}

JavaScript (jQuery):

$(document).scroll(function() {
  var y = $(this).scrollTop();
  if (y > 800) {
    $('.bottomMenu').fadeIn();
  } else {
    $('.bottomMenu').fadeOut();
  }
});

Explanation:

This script monitors the scroll position of the document. When the scroll position becomes greater than 800 pixels, it triggers the fade-in animation for the .bottomMenu div. Conversely, when the scroll position falls below 800 pixels, it triggers the fade-out animation.

The above is the detailed content of How to Show and Hide a Div Based on Scroll Position?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn