简体   繁体   中英

Javascript stopping scroll from jumping

I have a page where you can click to slideDown an element from the top of the page.

I am trying to create a rule that says if the push down is visible and the screen has scrolled further than the height of the push down then it should be hidden again. Meaning the user will have to push the button to get it to show again.

In my HTML I have:

<div class="row" id="learn-more" style="display:none">
  <div class="small-12 columns" id="close">
    <p id="close-learn">
      <i class="fa fa-times pull-right fa-2x"></i>
    </p>
  </div>
  <div class="small-12 columns" id="learn-content">
    <h1>Content for Pushdown</h1>
  </div>
</div>

<div class="row" id="hero">
  <div class="small-12 columns small-centered">
    <p id="learn"><a class="transition">Learn More</a></p>
  </div>
</div>

In my Javascript I have:

  // Open and close learn more section
  $("#learn").on("click", function() {
    $("#learn-more").slideDown();
  });

  $("#close-learn").on("click", function() {
    $("#learn-more").slideUp();
  });

  // Close learn-more based on scroll position
  $(window).on("scroll", function() {

    var scrollPosition = $(window).scrollTop();

    if ($("#learn-more").is(":visible") && scrollPosition > $("#learn-more").height()) {
      $("#learn-more").slideUp()
    } 
  });

This all works but when the #learn-more element slides up the page jumps down about 500 pixels which is the height of the #learn-more element. I would like mine to work in the same way as Airbnb's new homepage when you click the 'how it works' button and then scroll below the push down element.

Any advice would be much appreciated.

Seems that this situation occurs because $(window).scrollTop position is preserved after the the slideUp() is called. But we can memorize the visible position of Learn More button relative to the top of the window and after text block is hidden return to this position. Also, i suggest to use hide() instead of slideUp() here.

Here is what I suggest to do on scroll:

 $(window).on("scroll", function(event) {
      var scrollPosition = $(window).scrollTop();
      var learnMore = $("#learn-more");
      if (learnMore.is(":visible") && scrollPosition > learnMore.height()) {
             var learnMoreButtonTop = $("#learn").offset().top - scrollPosition;
             learnMore.hide();
             $(window).scrollTop(learnMoreButtonTop);
        } 
  });

Working example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM