luk
luk

Reputation: 139

jQuery scrollTop() executes multiple times

I have a code like below in my Javascript (jQuery) file:

jQuery(document).on('scroll', function() {
    var scrollTop = jQuery(document).scrollTop();
    console.log(scrollTop);
    if(scrollTop < 350) {
        jQuery('.header__top').removeClass('header-fixed');
        jQuery('.logo').css({position: "absolute", height: "auto"});
        jQuery('.logo img').css("height", "auto");
    }else {
        jQuery('.header__top').addClass('header-fixed');
        jQuery('.logo').css({position: "static", height: "85px"});
        jQuery('.logo img').css("height", "100%");
    }
});

And when I scroll 3 times in my browser something strange happens. Function fires multiple times (infinite). Then when I scroll top or down it works fine. Why is my scroll function causing infinite executes in a specyfic place?

Upvotes: 0

Views: 189

Answers (2)

luk
luk

Reputation: 139

I solve my problem, which was using display: flex and position:fixed on the same element.

Upvotes: 0

Velimir Tchatchevsky
Velimir Tchatchevsky

Reputation: 2815

The scoll event fires multiple times - that's the expected behavior. You should use the throttle/debounce (https://underscorejs.org/#throttle) functions to tackle this problem.

From MDN:

Since scroll events can fire at a high rate, the event handler shouldn't execute computationally expensive operations such as DOM modifications. Instead, it is recommended to throttle the event using requestAnimationFrame(), setTimeout() or a CustomEvent, as follows.

Upvotes: 3

Related Questions