Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
149
rated 0 times [  155] [ 6]  / answers: 1 / hits: 68807  / 11 Years ago, tue, april 9, 2013, 12:00:00

I'm playing with window.onpopstate, and there is a thing that annoys me:



Browsers tend to handle the popstate event differently on page load.
Chrome and Safari always emit a popstate event on page load, but
Firefox doesn't.



source


I tested it, and yeah, in Chrome and Safari 5.1+ the popstate event is fired on page load, but not in Firefox or IE10.


The problem is, that I want to listen only to popstate events where user clicked the back or forward button (or the history was changed via javascript), but don't want to do anything on pageload.


In other words, I want to differentiate the popstate event from page load from the other popstate events.


This is what I tried so far (I'm using jQuery):


$(function() {
console.log('document ready');

setTimeout(function() {
window.onpopstate = function(event) {
// Do something here
}, 10);
});

Basically I'm try to bind my listener function to popstate late enough to be not bound on page load, only later.


This seems to work; however, I don't like this solution. How can I be sure that the timeout chosen for setTimeout is big enough, but not too big (because I don't want it to wait too much).


I hope for a smarter solution!


More From » jquery

 Answers
10

Check for boolean truth of event.state in popstate event handler:



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


To ensure this will work, always specify a non-null state argument when calling history.pushState() or history.replaceState(). Also, consider using a wrapper library like History.js that provides consistent behavior across browsers.


[#79029] Monday, April 8, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
adrienkeithr

Total Points: 503
Total Questions: 126
Total Answers: 110

Location: Lithuania
Member since Fri, Sep 4, 2020
4 Years ago
;