A faster alternative to $ (window) .scroll?

I noticed that jQuery scroll binding for $ (window) .scroll tends to significantly reduce pages. For example, I have elements in the page change styles when I scroll through them using the following script:

$(window).scroll(function() {
     var bottom_of_window = $(window).scrollTop() + $(window).height();
     $('.ElementsToBeChanged').each(function() { 
            var bottom_of_object = $(this).offset().top + $(this).outerHeight();
            if (bottom_of_window > bottom_of_object) {
                //Add my styles
            }
        });

});

It is clear that the laggy site, since it constantly works on scrolling, but I did not come across any alternative for triggering events when objects scroll. Such sites that trigger events on a scroll look pretty often; What do they use to circumvent this gap?

+4
source share
1 answer

, , , .

, , 20 .

window [ex: win = $(window)] el this.

, css jQuery, / .

, , , . , , .

20 :

var win = $(window);

win.scroll(function() {
     var bottom_of_window = win.scrollTop() + win.height();
     $('.ElementsToBeChanged').each(function(index,el) { 
            var bottom_of_object = $(el).offset().top + $(el).outerHeight();
            if (bottom_of_window > bottom_of_object) {
                $(el).addClass('red');
            }else{
            		$(el).removeClass('red');
            }
        });

});
.ElementsToBeChanged{
  margin:100px;
  height:200px;
  border:1px solid black;
  transition:2s;
}

.ElementsToBeChanged.red{
  background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
<div class="ElementsToBeChanged">.ElementsToBeChanged</div>
Hide result

, , Skrollr.js ScrollMagic

0

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


All Articles