Search code examples
javascriptjquerybrowser-historyhistory.js

Different Ways to Bind a popstate Event


What is the difference between these three events?

1

 $(window).bind("popstate", function() {
     alert('popstate');
 });

2

 window.onpopstate =  function() {
     alert('popstate');
 }

3

window.addEventListener("popstate", function (event){
    if (event.state) {
        alert('popstate');
    }
});

Solution

  • There is no difference. All three are binding listeners to the popstate event. The first one uses the jQuery library, while the other two are vanilla JS.

    One small exception - the second method will replace any previous popstate event listener, while the other ones will just add a new one.