简体   繁体   中英

prevent jumping back to top of screen jQuery animate

I have two 'screens' with different background images.

when the user clicks on the down arrow it scrolls from one 'screen' to the one below. The second screen is set to display none at the beginning. This all works as expected, however, when trying to scroll to the top of the screen again it jumps to the top as opposed to smoothly scrolling back to the top. I am also using GSAPs tween library for other animations.

Please see code below:

JS

 $('.down-arrow').click(function() {
    var tl = new TimelineMax();
    tl.set('.background-two', {display: 'block', onComplete: scrollDown})
    tl.set('.background-one', {display: 'none', delay: 0.6})

    function scrollDown(){
          $('html, body').animate({scrollTop: $(window).height()}, 600);
    }

  });


  $('.up-arrow').click(function() {
    var tl = new TimelineMax();
    tl.set('.background-one', {display: 'block', onComplete: scrollUp})
    tl.set('.background-two', {display: 'none', delay: 0.6})
    function scrollUp(){
          $('html, body').animate({scrollTop: 0}, 600);
    }
  });

CSS

.background-one {
    background: url(../img/Background1.png) no-repeat center;
    background-size: cover;
    height: 100%;
    width: 100%;
    position: relative;
}

.background-two {
    background: url(../img/Background2.png) no-repeat center;
    background-size: cover;
    height: 100%;
    width: 100%;
    position: relative;
}

HTML

<div class="background-one">
   <div class="up-arrow">UP</div>
</div>
<div class="background-two">
   <div class="down-arrow">DOWN</div>
</div>

My guess is that when you set the top block to display: block; it appears immediately and pushes down your bottom block.

What you could try instead is sliding the blocks in (By animating their heights instead of scrolling).

Does it work when you properly close your html div-tags?

Edit:

I created a fiddle , the animation works fine. You're removing (display:none) the other element, which causes the page to flicker/jump.

function scrollDown(){
  $('html, body').animate({scrollTop: $(window).height()}, 600);
}
function scrollUp(){
  $('html, body').animate({scrollTop: 0}, 600);
}
$('.down-arrow').click(function() {
  var tl = new TimelineMax();
  tl.set('.background-two', {display: 'block', onComplete: scrollDown})
  tl.set('.background-one', {display: 'none', delay: 0.6})
  });


  $('.up-arrow').click(function() {
    var tl = new TimelineMax();
    tl.set('.background-one', {display: 'block', onComplete: scrollUp})
    tl.set('.background-two', {display: 'none', delay: 0.6})

  });

Tip: Keep your functions outside your click-handler.

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