S
S
Sergey Miller2018-04-20 20:33:39
JavaScript
Sergey Miller, 2018-04-20 20:33:39

What is wrong in the script?

The script works, but the animation lags hard, especially on weak laptops. A friend suggested that each time you don’t need to use it, I don’t understand then what the code should look like in the end. I do this: the animated element first in css has the property display:none , about reaching the scroll to the right place, in jquery I do fadeIn to the element and add a class in which the animation itself is written in css. Tell me what is wrong in the script and how it is done correctly, please.

$(document).ready(function() {
    var windowHeight = $(window).height();
    $(document).on('scroll', function() {
        $('#firstScroll').each(function() {
            var self = $(this),
                height = self.offset().top + self.height() + 50;
            if ($(document).scrollTop() + windowHeight >= height) {
                $('#firstGrid').addClass('fadeInDown').fadeIn(700);
            }
        });
        //цены в слайдере
        $('.strike-price').each(function() {
            var self = $(this),
                height = self.offset().top + self.height() + 100;
            if ($(document).scrollTop() + windowHeight >= height) {
                $('.for-price big').addClass('fadeInDownPrice').fadeIn(700);
            }
        });
        //слайдер отзывов
        $('#box6').each(function() {
            var self = $(this),
                height = self.offset().top + self.height();
            if ($(document).scrollTop() + windowHeight >= height) {
                $('.contacts').addClass('fadeInTop').fadeIn(700);
            }
        });
    });
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2018-04-20
@Stalker_RED

$(document).on('scroll' ...
this thing fires on EVERY scroll event. And there can be a LOT of them. To be sure, you can add console.log() and look at the flood.
Read about throttle/debounce
Going further:

$('#firstScroll').each(function() { ...
$('#box6').each(function() { ...
wtf? Do you have many elements with the same id there?
And every time you search the DOM for these elements, and for each you calculate the same data
$(document).scrollTop() + windowHeight
Why not find the elements in advance, do the calculations for the general calculations once for all?
Let's go deeper:
if (скролл больше чего-то там)  {|
  какойтоЭлемент.addClass('fadeInTop').fadeIn(700);
}
Seriously? That is, we scrolled to the right place, everything appeared beautifully, we spin the wheel further, and continue to spam .addClass().fadeIn() many times per second? Well, get hurt.
PS: sorry for being a little rude, I didn't have to run your porridge through jsbeautifier , otherwise my eyes started to bleed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question