-
Notifications
You must be signed in to change notification settings - Fork 0
/
author.js
76 lines (59 loc) · 2.6 KB
/
author.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
function appendAuthorToHTML() {
getRandomAuthor((randomAuthor) => {
const authorName = randomAuthor['name'];
const authorMail = randomAuthor['email'];
const authorPhoneNumber = randomAuthor['phone'];
const companyName = randomAuthor['company']['name'];
const authorContainer = document.querySelector("#author_container");
const authorNameParagraph = document.createElement("p");
authorNameParagraph.textContent = `Author: ${authorName}`;
authorNameParagraph.className = "author-field-item";
authorContainer.appendChild(authorNameParagraph);
const emailLabel = document.createTextNode("Email: ")
const authorMailAnchor = document.createElement("a");
authorMailAnchor.className = "link";
authorMailAnchor.href = `mailto:${authorMail}`;
authorMailAnchor.textContent = authorMail;
const span = document.createElement("span");
span.className = "author-field-item";
span.appendChild(emailLabel);
span.appendChild(authorMailAnchor);
authorContainer.appendChild(span);
const authorPhoneNumberParagraph = document.createElement("p");
authorPhoneNumberParagraph.textContent = `Phone Number: ${authorPhoneNumber}`;
authorPhoneNumberParagraph.className = "author-field-item";
authorContainer.appendChild(authorPhoneNumberParagraph);
const companyNameParagraph = document.createElement("p");
companyNameParagraph.textContent = `Company: ${companyName}`;
companyNameParagraph.className = "author-field-item";
authorContainer.appendChild(companyNameParagraph);
}).then();
}
async function getRandomAuthor(callback) {
await fetchAuthors((authors) => {
const randomIndex = Math.floor(Math.random() * authors.length);
const randomAuthor = authors[randomIndex];
callback(randomAuthor);
});
}
async function fetchAuthors(callback) {
try {
const url = "https://jsonplaceholder.typicode.com/users";
const response = await fetch(url);
// Check if the response is ok (status 200-299)
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Parse the JSON from the response
const data = await response.json();
// Log the data
console.log(data);
// callback
callback(data);
} catch (error) {
// Handle errors
console.error('Error fetching data:', error);
}
}
// Run the function on page load
document.addEventListener('DOMContentLoaded', appendAuthorToHTML);