3

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.

Anil
  • 3,722
  • 2
  • 24
  • 49
Sunny Chaudhari
  • 400
  • 1
  • 5
  • 19

2 Answers2

1

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);
Anil
  • 3,722
  • 2
  • 24
  • 49
0
<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.

Javi Zhu
  • 68
  • 8
  • I have given the complete script in my question itself. The issue is when you scroll, it executes window.scroll function but also executes "onpopstate" function which I want to prevent. – Sunny Chaudhari Mar 15 '17 at 07:51