Simply binding the window (in jQuery) to popstate, the event is always triggered twice.
$( window ).bind( 'popstate', myFunction );
There's nothing in myFunction() to cause this - I've tried stripping out this function to a simple:
console.log( 'triggered' );
And the result is the same. It's always triggered twice (tested in Safari, Chrome & Firefox).
I know there are issues with the HTML5 history API, but any advice other than 'try History.js' would be gratefully received!
Ok, I figured out a way to solve this:
jQuery( function( $ ){
var currentPageNo = location.hash || 1;
var myFunction = function(){
var pageNo = location.hash;
if( pageNo != currentPageNo ){
// trigger AJAX stuff here
currentPageNo = pageNo;
}
};
$( window ).bind( 'popstate', myFunction );
});
Only triggers the function once, but the state is still triggered twice!
This does not answer the question directly, but it might be of help to others who find this question. Because I only needed to listen for the popstate once, and remove the listener immediately.
If you want to dispose of the listener after it has been triggered (only once), you can add the following object to the third parameter of addEventListener:
window.addEventListener('popstate', myFunction, {once: true});
once
A Boolean indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.
Here is the documentation: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With