forked from HackYourFuture/JavaScript3_examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
75 lines (64 loc) · 1.91 KB
/
app.js
File metadata and controls
75 lines (64 loc) · 1.91 KB
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
/*
1. Refine the createAndAppend() function signature (i.e. the parameter list).
2. Add disabled <option>, selected by default
3. Render errors to the page
*/
'use strict';
{
const API_BASE_URL = 'http://api.nobelprize.org/v1';
function fetchJSON(url, cb) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status <= 299) {
cb(null, xhr.response);
} else {
cb(new Error(`Network error: ${xhr.status} - ${xhr.statusText}`));
}
};
xhr.onerror = () => cb(new Error('Network request failed'));
xhr.send();
}
function createAndAppend(name, parent, options = {}) {
const elem = document.createElement(name);
parent.appendChild(elem);
Object.keys(options).forEach(key => {
const value = options[key];
if (key === 'text') {
elem.textContent = value;
} else {
elem.setAttribute(key, value);
}
});
return elem;
}
function main() {
const root = document.getElementById('root');
fetchJSON(`${API_BASE_URL}/country.json`, (err, data) => {
if (err) {
createAndAppend('div', root, { text: err.message });
return;
}
const select = createAndAppend('select', root);
createAndAppend('option', select, {
text: 'Select a country',
disabled: 'disabled',
selected: 'selected',
});
const countries = data.countries.sort((a, b) => a.name.localeCompare(b.name));
countries.forEach((country, index) => {
createAndAppend('option', select, {
text: country.name,
value: index,
});
});
const p = createAndAppend('p', root);
select.addEventListener('change', () => {
const country = data.countries[select.value].name;
p.textContent = country;
});
});
}
window.onload = main;
}