-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.js
48 lines (37 loc) · 1.38 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
// Information to reach API
const url = 'https://api.rebrandly.com/v1/links';
const apiKey = "ef569fae7b60430dad4392d9a63cd7c4";
// Some page elements
const inputField = document.querySelector('#input');
const shortenButton = document.querySelector('#shorten');
const responseField = document.querySelector('#responseField');
// AJAX functions
const shortenUrl = () => {
const urlToShorten = inputField.value;
const data = JSON.stringify({destination: urlToShorten});
const xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
renderResponse(xhr.response);
}
}
xhr.open('POST', url);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.setRequestHeader('apikey', apiKey);
xhr.send(data);
}
// Clear page and call AJAX functions
const displayShortUrl = (event) => {
event.preventDefault();
var result = document.getElementById("responseField");
result.classList.remove("result-hidden");
result.classList.add("result-show");
document.getElementById("shorten").classList.add("shorten-hidden");
const retryButton = document.querySelector('#retry');
while(responseField.firstChild){
responseField.removeChild(responseField.firstChild);
}
shortenUrl();
}
shortenButton.addEventListener('click', displayShortUrl);