jQuery button slide in and out on scroll

Viewed 784

I am trying to slide in a button when the scroll position is between two pxiel values and slides out when its not. The following code is not really working as the button sometimes slides in and sometimes not and most of the time not between the defined pixel values .. is this a script loading issue or is my jQuery code wrong?

  var y = jQuery(this).scrollTop();
  if (y > 700 && y < 1300) {
    jQuery('.side-button-wrap').animate({ left: '0px' });
  } else {
    jQuery('.side-button-wrap').animate({ left: '-200px' });
  }
});´´´
1 Answers

The issue is because the -200px setting is cumulative. As a result every time the scroll event fires you move the element a further 200px to the left.

To fix this you need to make the action idempotent. In other words, no matter how many times the event fires the result needs to be the same. To achieve that use CSS to perform the transition to a fixed position. Then just toggle the relevant class based on the vertical scroll position. Try this:

$(window).on('scroll', function() {
  var y = jQuery(this).scrollTop();
  $('.side-button-wrap').toggleClass('slide-in', y > 700 && y < 1300)
});
html,
body {
  height: 3000px;
}

.side-button-wrap {
  position: fixed;
  top: 20px;
  right: -100px;
  width 100px;
  transition: right 0.3s;
}

.side-button-wrap.slide-in {
  right: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Scroll down!
<div class="side-button-wrap">
  <button>Lorem ipsum</button>
</div>

You may also want to look in to debouncing the scroll event as it can lead to performance issues, but that depends on how complex the DOM is with regard to the elements being animated.

Related