Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent executing window.onpopstate function while window.scroll event using jquery

The scenario is when I scroll in browser it executes

$(window).scroll(function() { ...  }

but in same page I have onpopstate function which usually executes when I press back/forward button in browser

window.onpopstate = function(event) { ...  }

Here is my complete script on html page

<script>
    window.onpopstate = function(event) { ...  }

    $( document ).ready(function() {
        $(window).scroll(function() { ...  }
    });
</script>

Issue is when I scroll in browser it executes $(window).scroll as well as window.onpopstate both the events.

Can anyone help me out here, as how do I prevent executing window.onpopstate event while scrolling.

like image 971
Sunny Chaudhari Avatar asked Dec 08 '25 08:12

Sunny Chaudhari


1 Answers

The $(window).scroll event always raises the popstate event and we should not stop this by using event propagation, as A popstate event is dispatched to the window every time the active history entry changes between two history entries for the same document. refer details on MDN

The solution here can be be to put a check in popstate 's handler like
when event.state is not null then do your job else skip

window.addEventListener('popstate', function(event) {
        if (event.state) {
            -- do your job
        }
    }, false);
like image 170
Anil Avatar answered Dec 10 '25 23:12

Anil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!