-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
44 lines (38 loc) · 1.11 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
// Information to reach API
const apiKey = '<Your API>';
const url = 'https://api.rebrandly.com/v1/links';
// Some page elements
const inputField = document.querySelector('#input');
const shortenButton = document.querySelector('#shorten');
const responseField = document.querySelector('#responseField');
// Asynchronous functions
const shortenUrl = () => {
const urlToShorten = inputField.value;
const data = JSON.stringify({destination: urlToShorten});
fetch(url, {
method: 'POST',
headers: {
'Content-type': 'application/json',
'apikey': apiKey
},
body: data
}).then(response => {
if(response.ok) {
return response.json();
}
throw new Error('Request failed!')
}, networkError => {
console.log(networkError.message);
}).then(jsonResponse => {
renderResponse(jsonResponse);
})
}
// Clear page and call Asynchronous functions
const displayShortUrl = (event) => {
event.preventDefault();
while(responseField.firstChild){
responseField.removeChild(responseField.firstChild);
}
shortenUrl();
}
shortenButton.addEventListener('click', displayShortUrl);