-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
64 lines (52 loc) · 1.74 KB
/
script.js
File metadata and controls
64 lines (52 loc) · 1.74 KB
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
async function translateText() {
const key = document.getElementById("apiKey").value;
const region = document.getElementById("region").value;
const text = document.getElementById("inputText").value;
const targetLang = document.getElementById("targetLang").value;
const output = document.getElementById("output");
if (!key || !region || !text) {
alert("Fill all fields!");
return;
}
const endpoint = `https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=${targetLang}`;
try {
// Animated loading dots
let dots = 0;
output.classList.remove("show");
const loading = setInterval(() => {
dots = (dots + 1) % 4;
output.innerText = "Translating" + ".".repeat(dots);
}, 300);
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Ocp-Apim-Subscription-Key": key,
"Ocp-Apim-Subscription-Region": region,
"Content-Type": "application/json"
},
body: JSON.stringify([{ Text: text }])
});
clearInterval(loading);
const data = await response.json();
const translatedText = data[0].translations[0].text;
setTimeout(() => {
typeEffect(output, translatedText);
output.classList.add("show");
}, 200);
} catch (error) {
output.innerText = "Error!";
}
}
/* Typing animation */
function typeEffect(element, text) {
element.innerText = "";
let i = 0;
function typing() {
if (i < text.length) {
element.innerText += text.charAt(i);
i++;
setTimeout(typing, 25);
}
}
typing();
}