-
Notifications
You must be signed in to change notification settings - Fork 0
/
url.js
44 lines (39 loc) · 1.35 KB
/
url.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
const selectElement = (selector) => {
const element = document.querySelector(selector);
if (element) return element;
throw new Error(`Cannot find the element ${selector}`);
};
const form = selectElement("form");
const input = selectElement("input");
const result = selectElement(".result");
const hamburger = selectElement(".hamburger");
const navMenu = selectElement(".nav-menu");
hamburger.addEventListener("click", () => {
hamburger.classList.toggle("active");
navMenu.classList.toggle("active");
});
form.addEventListener("submit", (e) => {
e.preventDefault();
const url = input.value;
shortenUrl(url);
});
async function shortenUrl(url) {
try {
const res = await fetch(`https://api.shrtco.de/v2/shorten?url=${url}`);
const data = await res.json();
const newUrl = document.createElement("div");
newUrl.classList.add("item");
newUrl.innerHTML = `
<p> ${data.result.short_link}</p>
<button class="newUrl-btn" >Copy</button>
`;
result.prepend(newUrl);
const copyBtn = result.querySelector(".newUrl-btn");
copyBtn.addEventListener("click", () => {
navigator.clipboard.writeText(copyBtn.previousElementSibling.textContent);
});
input.value = "";
} catch (err) {
console.log(err);
}
}