-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
70 lines (65 loc) · 2.54 KB
/
script.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
const fromText = document.querySelector(".from-text"),
toText = document.querySelector(".to-text"),
exchageIcon = document.querySelector(".exchange"),
selectTag = document.querySelectorAll("select"),
icons = document.querySelectorAll(".row i");
translateBtn = document.querySelector("button"),
selectTag.forEach((tag, id) => {
for (let country_code in countries) {
let selected = id == 0 ? country_code == "en-GB" ? "selected" : "" : country_code == "hi-IN" ? "selected" : "";
let option = `<option ${selected} value="${country_code}">${countries[country_code]}</option>`;
tag.insertAdjacentHTML("beforeend", option);
}
});
exchageIcon.addEventListener("click", () => {
let tempText = fromText.value,
tempLang = selectTag[0].value;
fromText.value = toText.value;
toText.value = tempText;
selectTag[0].value = selectTag[1].value;
selectTag[1].value = tempLang;
});
fromText.addEventListener("keyup", () => {
if(!fromText.value) {
toText.value = "";
}
});
translateBtn.addEventListener("click", () => {
let text = fromText.value.trim(),
translateFrom = selectTag[0].value,
translateTo = selectTag[1].value;
if(!text) return;
toText.setAttribute("placeholder", "Translating...");
let apiUrl = `https://api.mymemory.translated.net/get?q=${text}&langpair=${translateFrom}|${translateTo}`;
fetch(apiUrl).then(res => res.json()).then(data => {
toText.value = data.responseData.translatedText;
data.matches.forEach(data => {
if(data.id === 0) {
toText.value = data.translation;
}
});
toText.setAttribute("placeholder", "Translation");
});
});
icons.forEach(icon => {
icon.addEventListener("click", ({target}) => {
if(!fromText.value || !toText.value) return;
if(target.classList.contains("fa-copy")) {
if(target.id == "from") {
navigator.clipboard.writeText(fromText.value);
} else {
navigator.clipboard.writeText(toText.value);
}
} else {
let utterance;
if(target.id == "from") {
utterance = new SpeechSynthesisUtterance(fromText.value);
utterance.lang = selectTag[0].value;
} else {
utterance = new SpeechSynthesisUtterance(toText.value);
utterance.lang = selectTag[1].value;
}
speechSynthesis.speak(utterance);
}
});
});