-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
82 lines (70 loc) · 2.79 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const selectTag = document.querySelectorAll("select");
const exchangeIcon = document.querySelector(".exchange");
const translateBtn = document.querySelector("button");
const fromText = document.querySelector(".from-text");
const toText = document.querySelector(".to-text");
const icons = document.querySelectorAll(".row i");
selectTag.forEach( (tag, id) => {
for (const country_code in countries) {
//Selecting En as default language for FROM and HI as TO
let selected;
if(id ==0 && country_code == "en-GB"){
selected = "selected";
}
else if(id ==1 && country_code == "ur-PK"){
selected = "selected";
}
let option = `<option value="${country_code}" ${selected}>${countries[country_code]}</option>`;
tag.insertAdjacentHTML("beforeend", option); //Adding Option Tag inside Select Tag
}
});
exchangeIcon.addEventListener("click", ()=>{
// Exchanging text area and select tag values.
let tempText = fromText.value;
let tempLang = selectTag[0].value;
fromText.value = toText.value;
selectTag[0].value = selectTag[1].value;
selectTag[1].value = tempLang;
toText.value = tempText;
});
translateBtn.addEventListener("click", () => {
let text = fromText.value;
let translateFrom = selectTag[0].value; //Getting from select tag value
let translateTo = selectTag[1].value; //Getting to select tag value
if(!text) return;
toText.setAttribute("placeholder", "Translating...");
let apiUrl = `https://api.mymemory.translated.net/get?q=${text}&langpair=${translateFrom}|${translateTo}`;
// Fetching API response and returnuing it with parsing into JS Object and in another then method
// Receiveing it
fetch(apiUrl).then(res => res.json()).then(data => {
toText.value = data.responseData.translatedText;
toText.setAttribute("placeholder", "Translation");
})
});
icons.forEach(icon => {
icon.addEventListener("click", ({target})=>{
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); //Speak the passed utterance
}
});
});
//https://mymemory.translated.net/doc/spec.php