Decreased performance when a scrollTop-based item fades

I saw several websites with this effect, however, it seems that he lost the frame rate in my attempt. I basically want to change the opacity of the element, the more the user scrolls.

$(window).scroll(function(event){
        $("#responsive-slider-with-blocks-1").css("opacity", 1 - $(window).scrollTop() / 1500);
      }

Is there a better way to do this? (Ace would be just CSS, but not possible).

I'm really not a fan of scroll event bindings.

Edit:

Due to a change in the opacity of an element that spans the entire viewport, there may be a reason why the frame rate drops. Could fading into the black div covering an element not reduce the frame rate so much?

+4
source share
2 answers

, , . docs :

, , DOM. , requestAnimationFrame, setTimeout customEvent...

, , ( jquery ):

var last_known_scroll_position = 0;
var ticking = false;

var responsiveSlider = document.getElementById('responsive-slider-with-blocks-1');
function doSomething(scroll_pos) {
  responsiveSlider.style.opacity = 1 - scroll_pos / 1500;
}

window.addEventListener('scroll', function(e) {
  last_known_scroll_position = window.scrollY;
  if (!ticking) {
    window.requestAnimationFrame(function() {
      doSomething(last_known_scroll_position);
      ticking = false;
    });
  }
  ticking = true;
});

, , , , , - , .

+3

, , , . jQuery DOM . .

, .

  • , DOM, jQuery . , jQuery DOM .

  • .

  • , . , , , , .

+1

Source: https://habr.com/ru/post/1684367/


All Articles