cup_of
cup_of

Reputation: 6697

Resize function won't work with check width and scroll function

I have a check width function that checks the width of a screen then performs a scroll function.

Here is the code:

jQuery(window).on('resize', checkWidthStickyHeader);
function checkWidthStickyHeader() {
    if (jQuery(window).width() > 1350) {
        jQuery(window).scroll(function () {
            if (jQuery(window).scrollTop() > 50) {
                jQuery('.header-top').addClass('header-top-active');
            }
            else {
                jQuery('.header-top').removeClass('header-top-active');
            }
        });
    } else {
        
    }
}
checkWidthStickyHeader();

So basically what this is saying, is that if the browser is above 1350px then perform a scroll function. If it is less than 1350px then do nothing.

This works, but you have to refresh the page for it to check the width of the window again.

To have it check the width on resize I added that thing at the top jQuery(window).on('resize', checkWidthStickyHeader).

This seems to work because I did a console.log test in the else statement at the bottom and that was firing every time I resized the window.

But here is the issue, when you start at a screen width bigger than 1350px and the shrink it to a value below that, the scroll function still fires. I'm not sure why it does this.

Upvotes: 0

Views: 47

Answers (1)

karthick
karthick

Reputation: 12176

You either have to unregister your scrollHandler or check the width inside the scroll function.

Example: Register/unregister scroll
jQuery(window).on('resize', checkWidthStickyHeader);


    function addStickyness(){
                    if (jQuery(window).scrollTop() > 50) {
                        jQuery('.header-top').addClass('header-top-active');
                    }
                    else {
                        jQuery('.header-top').removeClass('header-top-active');
                    }
        }

    function checkWidthStickyHeader() {
        if (jQuery(window).width() > 1350) {
            jQuery(window).on('scroll',addStickyness);
        } else {
            jQuery(window).off('scroll', addStickyness)
        }
    }
    checkWidthStickyHeader();

Upvotes: 1

Related Questions