forked from heyitsolivia/secretpuppies
-
Notifications
You must be signed in to change notification settings - Fork 0
/
application.js
82 lines (66 loc) · 2.05 KB
/
application.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
$(document).ready(function() {
$.getJSON("puppies.json", playPuppies)
});
function playPuppies(puppies) {
var puppies_seen = [];
var keycodes = {
spacebar: 32,
left_arrow: 37,
right_arrow: 39
}
function pickUpPuppy() {
var puppyCount = puppies.length;
return puppies[Math.floor(Math.random() * puppyCount)];
}
function makeURL(newPup) {
return 'https://i.imgur.com/' + newPup + '.mp4';
}
function newPuppy() {
if (puppies_seen.length == puppies.length) {
console.log("Ran out of puppies. What should I do?");
var current_pup = puppies_seen[puppies_seen.length - 1];
puppies_seen = [current_pup]; // for now reset but don't repeat what we have
}
var newPup = pickUpPuppy();
while (puppies_seen.indexOf(newPup) != -1) {
newPup = pickUpPuppy();
}
puppies_seen.push(newPup);
return newPup;
}
function showPuppy(newPup) {
var url = makeURL(newPup);
$('#puppy > source').attr('src', url);
$('.permalink').attr('href', url);
$('#puppy').load();
}
function loadPuppy(pup) {
showPuppy(pup)
history.pushState({pup: pup}, '', '#' + pup);
}
function initialPuppy(pup) {
showPuppy(pup);
history.replaceState({pup: pup}, '', '#' + pup);
}
$(document).keyup(function(evt) {
if (evt.keyCode == keycodes.spacebar) {
var newPup = newPuppy();
loadPuppy(newPup);
} else if (evt.keyCode == keycodes.left_arrow) {
history.back();
} else if (evt.keyCode == keycodes.right_arrow) {
history.forward();
}
});
window.addEventListener('popstate', function(e) {
if (e.state && e.state.pup) {
showPuppy(e.state.pup);
}
})
var initial_pup = window.location.hash.substring(1);
if (puppies.indexOf(initial_pup) != -1) {
initialPuppy(initial_pup);
} else {
initialPuppy(newPuppy());
}
}