0

I wrote a small jquery code which fades out an overlay by changing the opacity while scrolling down. I thought everything was working fine, but unfortunately on some, obviously older, PCs the fade effect isn't smooth and stutters. However on my PC everything is perfect.

Here my script:

$(window).on('scroll', function() {
    var scrollTop = $(this).scrollTop();

    if($('.overlay').is(':visible') || (scrollTop < lastScrollTop)){
        if ($(this).scrollTop() < 150) {
            $('.overlay').show();
            $('.overlay').css('opacity', (150 - $(this).scrollTop()) / 150);
            $('.container-gesamt').css('padding-top', $(this).scrollTop());
        }else{
            $('.overlay').hide();
        }
    }
    lastScrollTop = scrollTop;
});

To my mind it must be a problem of older hardware, or what do you think?
And if so, do you know if there is a way to make the effect smooth on older hardware?

DarkBee
  • 16,592
  • 6
  • 46
  • 58
Christian
  • 63
  • 9

1 Answers1

1

Some small performance improvements could be

const $overlay = $('.overlay');
const $window = $(window);
const $container = $('.container-gesamt');
const overlayIsVisible = $overlay.is(':visible');

$window.on('scroll', function() {
  const scrollTop = $window.scrollTop();

  if (overlayIsVisible || (scrollTop < lastScrollTop)) {
    if (scrollTop < 150) {
      if (!overlayIsVisible) {
        $overlay.show();
        overlayIsVisible = true;
      }
      $overlay.css('opacity', (150 - scrollTop) / 150);
      $container.css('padding-top', scrollTop);
    } else {
      if (overlayIsVisible) {
        $overlay.hide();
        overlayIsVisible = false;
      }
    }
  }
  lastScrollTop = scrollTop;
});
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317