26

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/

John
  • 10,154
  • 9
  • 79
  • 143
Caio Tarifa
  • 5,743
  • 11
  • 44
  • 70

1 Answers1

47

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)
pimvdb
  • 141,012
  • 68
  • 291
  • 345
  • @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: http://jsfiddle.net/pimvdb/un4Xk/2/. – pimvdb Oct 22 '11 at 16:51
  • Could you explain what this line does? `var initialPop = !popped && location.href == initialURL;` – Andriy Drozdyuk Jan 30 '12 at 17:52
  • @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: http://jsfiddle.net/un4Xk/3/. – pimvdb Jan 30 '12 at 21:46
  • 4
    Unfortunately, all Fiddles have lost their strings :( – ᴠɪɴᴄᴇɴᴛ Feb 20 '15 at 10:41
  • change your jsfiddle link – Prashant Tapase Mar 20 '15 at 10:12