-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
66 lines (62 loc) · 2.52 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
const fromText = document.querySelector(".from-text"),
toText = document.querySelector(".to-text")
selectTag = document.querySelectorAll("select"),
exchangeIcon = document.querySelector(".exchange"),
translateBtn = document.querySelector("button"),
icons = document.querySelectorAll(".row i");
selectTag.forEach((tag, id) => {
for(const country_code in countries) {
//selecting English by default as FROM language and HINDI as TO language
let selected;
if(id == 0 && country_code == 'en-GB') {
selected = "selected";
}
else if(id == 1 && country_code == "hi-IN") {
selected = "selected";
}
let option = `<option value="${country_code}" ${selected}>${countries[country_code]}</option>`;
tag.insertAdjacentHTML("beforeend", option); //adding options inside select tag
}
})
exchangeIcon.addEventListener("click", () => {
let tempText = fromText.value,
tempLang = selectTag[0].value;
fromText.value = toText.value;
selectTag[0].value = selectTag[1].value;
toText.value = tempText;
selectTag[1].value = tempLang;
})
translateBtn.addEventListener("click", () => {
let text = fromText.value,
translateFrom = selectTag[0].value,
translateTo = selectTag[1].value;
let apiURL = `https://api.mymemory.translated.net/get?q=${text}!&langpair=${translateFrom}|${translateTo}`;
//fetching api response and returning it with parsing into js obj and in another then method receiving that obj
fetch(apiURL).then(res => res.json()).then(data => {
toText.value = data.responseData.translatedText;
});
});
icons.forEach(icon => {
icon.addEventListener("click", ({target}) => {
if(target.classList.contains("fa-copy")) {
if(target.id == 'from') {
navigator.clipboard.writeText(fromText.value); //writeText specifies the text string to the system clipboard
}
else {
navigator.clipboard.writeText(toText.value);
}
}
else {
let utterance;
if(target.id == "from") {
utterance = new SpeechSynthesisUtterance(fromText.value);
utterance.lang = selectTag[0].value; //setting the language
}
else {
utterance = new SpeechSynthesisUtterance(toText.value);
utterance.lang = selectTag[1].value;
}
speechSynthesis.speak(utterance);
}
});
})