Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

binding window to popstate event triggered twice

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!

like image 308
Richard Sweeney Avatar asked Dec 16 '22 04:12

Richard Sweeney


2 Answers

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!

like image 170
Richard Sweeney Avatar answered Jan 11 '23 13:01

Richard Sweeney


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

like image 39
John Avatar answered Jan 11 '23 12:01

John