Reputation: 430
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.
Upvotes: 3
Views: 2380
Reputation: 3752
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);
Upvotes: 1
Reputation: 68
<script type="text/javascript">
window.onpopstate = function(event) {
alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
}
$(document).ready(function () {
$(window).scroll(function () {
alert(2);
});
});
history.pushState({ page: 1 }, "title 1", "?page=1");
history.pushState({ page: 2 }, "title 2", "?page=2");
history.replaceState({ page: 3 }, "title 3", "?page=3");
history.back();
history.back();
history.go(2);
</script>
I also testing, but without this issue.
If you can provide detail code.
Upvotes: 0