-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.js
88 lines (70 loc) · 2.43 KB
/
main.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
$(document).ready(function() {
// Helpers //
var randBetween = function(start, end) {
return Math.floor(Math.random() * end) + start;
};
var stripTags = function(html) {
return html.replace(/(<([^>]+)>)/ig, '').split(":")[0];
};
// Pronunciation //
// Prepare <audio> tag for playback
var setupAudioPlayer = function(audioUrl) {
var $player = $(".audio-playback");
var player = $player[0]
player.src = audioUrl;
player.load();
player.play();
var playerClasses = "player-ready player-playing player-error";
$player.on("playing", function() {
$(".player").removeClass(playerClasses);
$(".player").addClass("player-playing");
});
$player.on("ended", function() {
$(".player").removeClass(playerClasses);
$(".player").addClass("player-ready");
});
}
// Retrieve audio pronunciation URL from Wordnik and trigger player setup
var setupAudio = function(word) {
apiKey = "rce897rlum8g7wn0otc3b9ut0b5yu11cu1nt8b9ir4t8wg0kv";
apiUrl = "http://api.wordnik.com:80/v4/word.json/" + word + "/audio?useCanonical=true&limit=3&api_key=" + apiKey;
$.ajax({
url: apiUrl,
success: function(data) {
if (data.length) {
audioUrl = data[0].fileUrl;
setupAudioPlayer(audioUrl);
}
}
});
}
// Main App //
// Retrieve random word and update HTML
var successCallback = function(data) {
wordCount = data.length - 1;
wordIndex = randBetween(0, wordCount);
wordData = data[wordIndex].back;
$(".loading").hide();
$("#word").text(wordData[0].content);
$(".page-title").html(wordData[0].content + " (" + stripTags(wordData[1].content) + ")");
$("#definition").html(wordData[1].content);
$("#sentence").html(wordData[2].content);
$("#pronounce").data('word', wordData[0].content)
if (!navigator.onLine) {
$(".player").removeClass("player-ready");
$(".player").addClass("player-error");
$(".player").attr("title", "Pronunciation requires an internet connection.")
}
};
// Attach event listener to pronunciation button
$("#pronounce").click(function(e) {
var word = $(e.currentTarget).data('word');
// Only setup audio player if they have internet
if (navigator.onLine) {
// TODO: add a URL cache here to avoid multiple API calls
setupAudio(word);
}
});
// Load word content from JSON file
$.getJSON('words.json', successCallback);
});