forked from lesjames/history-api-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
112 lines (78 loc) · 3.32 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// guard against browsers w/o pushState (beware Android 2 & iOS 4)
if (window.history && 'pushState' in history) {
// encapsulate with an IIFE
(function () {
// because JSHint told me to
'use strict';
function displayContent(state, reverse) {
// change the page title
document.title = state.title;
// replace the current content
//$('.content').html(state.content);
//$('.photo').attr('src', state.photo);
// clone the current wrapper
var $clone = $('.wrapper').clone();
// replace the content in the clone
$clone.find('.content').html(state.content);
$clone.find('.photo').attr('src', state.photo);
$('.wrapper')
// add transition class to current wrapper
.addClass((!reverse) ? 'transition-out' : 'transition-in')
// append clone after current wrapper and add a transition class
.after($clone.addClass((!reverse) ? 'transition-in' : 'transition-out'))
// when finished animating remove old wrapper
.one('webkitTransitionEnd', function () {
$(this).remove();
});
// animate new content in after short delay
setTimeout(function () {
$clone.removeClass((!reverse) ? 'transition-in' : 'transition-out');
}, 200);
}
// create a state object from html
function createState($content) {
// create state object - 2013-03-10: browsers apparently
// ignore "title", but we should keep this anyway in case they
// start caring
var state = {
content : $content.find('.content').html(),
photo : $content.find('.photo').attr('src'),
title : $content.filter('title').text()
};
// return the object
return state;
}
// handle click on link
$(document).on('click', 'a', function (evt) {
// prevent normal navigation
evt.preventDefault();
// request new page through ajax
var req = $.ajax(this.href);
// what to do with ajax success
req.done(function (data) {
// create state object
var state = createState($(data));
// change the page content
displayContent(state);
// push the state into history
history.pushState(state, state.title, evt.target.href);
});
// what to do if ajax fails
req.fail(function () {
// revert to normal navigaiton
document.location = evt.target.href;
});
});
// handle forward/back buttons
window.onpopstate = function(evt) {
// guard against popstate event on chrome init
if (evt.state) {
// get the state and change the page content
displayContent(evt.state, true);
}
};
// create state on page init and replace the current history with it
var state = createState( $('title, body') );
history.replaceState(state, document.title, document.location.href);
}());
}