popstate returns event.state is undefined

21,496

event is the jQuery event object, not the DOM one.

To access the DOM event object, use event.originalEvent: http://jsfiddle.net/pimvdb/un4Xk/1/.

var state = event.originalEvent.state;

Remember that the state is only defined when the new state has data, so it is not available when clicking and then going back to the initial state:

  1. initial state
  2. link to state 1
  3. back button to initial state (no data available)

It is, however, available when clicking, clicking another time and then going back:

  1. initial state
  2. link to state 1
  3. link to state 2
  4. back button to state 1 (data available)
Share:
21,496

Related videos on Youtube

Caio Tarifa
Author by

Caio Tarifa

Updated on July 09, 2022

Comments

  • Caio Tarifa
    Caio Tarifa almost 2 years

    I am learning about history in HTML5, in this example (open the JavaScript browser console to see error) the event.state.url returns:

    Uncaught TypeError: Cannot read property 'url' of undefined
    

    Look and help: http://jsfiddle.net/un4Xk/

    • Yellow and Red
      Yellow and Red about 6 years
      url doesnot exists any more
  • pimvdb
    pimvdb over 12 years
    @Caio Tarifa: Well, the initial state is the one when the page loads, so you know that it should revert things back to the original state. E.g. in this case #return should be emptied back: jsfiddle.net/pimvdb/un4Xk/2.
  • Andriy Drozdyuk
    Andriy Drozdyuk over 12 years
    Could you explain what this line does? var initialPop = !popped && location.href == initialURL;
  • pimvdb
    pimvdb over 12 years
    @drozzy: I don't know for sure. It was part of @Caio Tarifa's original code as he posted in the question. It looks like it's to prevent the code from executing when the page is initially loaded, as popstate is executed as well in that case: jsfiddle.net/un4Xk/3.
  • ᴠɪɴᴄᴇɴᴛ
    ᴠɪɴᴄᴇɴᴛ about 9 years
    Unfortunately, all Fiddles have lost their strings :(
  • Prashant Tapase
    Prashant Tapase about 9 years
    change your jsfiddle link