Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

95
Views
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.

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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);
about 4 years ago · Santiago Trujillo Report

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!