Search code examples
jquerywordpresssticky

Window resize function not firing. Just to make sure it still does said function inside if resized less than and then above


I've just been working on a sticky nav when screen is scrolled below 550px. I've got the function working but when window is resized to below 992px it's meant to stop being sticky then if again resized above it should work but if I go back to below 992px it stays sticky so I believe the resize isn't working. See code below:

    if ($(window).width() >= 992) {

    $(document).scroll(function () {
        var y = $(document).scrollTop(), //get page y value
            header = $(".menu-faq-nav-container");
        if (y >= 550) {
            header.css({position: "fixed", top: "0", right: "50px"});
        } else {
            header.css({position: "relative", right: "0"});
        }
    });
} else {}

$(window).resize(function () {

    if ($(window).width() >= 992) {

        $(document).scroll(function () {
            var y = $(document).scrollTop(), //get page y value
                header = $(".menu-faq-nav-container");
            if (y >= 550) {
                header.css({position: "fixed", top: "0", right: "50px"});
            } else {
                header.css({position: "relative", right: "0"});
            }
        });
    } else {}
});

Any Ideas?


Solution

  • The main concern with this question is the duplicate event bindings. You are creating a new scroll event binding every time the resize happens, provided the width is larger than your desired minimum value. This means each scroll event it going to be processed multiple times, in an identical manner. Which means you're doing too much work, and can lead to issues.

    Also, once you fall below your minimum desired width, those scroll events do not go away. They still exist. So in order to removed the duplicate scroll event bindings, and to solve the issue of the scroll event handler processing when it should not, you should consider binding the scroll event handler once, and check the window width inside it. A which point you do not care about the resize event. The width is either above your minimum width or it is not.