Real-time Language Translator JavaScript, API

👤 Sharing: AI
```javascript
<!DOCTYPE html>
<html>
<head>
    <title>Real-time Language Translator</title>
    <style>
        body {
            font-family: sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20px;
        }

        textarea {
            width: 500px;
            height: 150px;
            margin-bottom: 10px;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            resize: none;
        }

        select {
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin-bottom: 10px;
        }

        button {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin-bottom: 10px;
        }

        button:hover {
            background-color: #3e8e41;
        }

        #translation {
            width: 500px;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            background-color: #f9f9f9;
            min-height: 50px;
        }

        .error {
            color: red;
        }
    </style>
</head>
<body>
    <h1>Real-time Language Translator</h1>

    <textarea id="inputText" placeholder="Enter text to translate..."></textarea>

    <select id="targetLanguage">
        <option value="en">English</option>
        <option value="es">Spanish</option>
        <option value="fr">French</option>
        <option value="de">German</option>
        <option value="ja">Japanese</option>
        <option value="zh-CN">Chinese (Simplified)</option>
        <option value="ru">Russian</option>
        <option value="ar">Arabic</option>
    </select>

    <button id="translateButton">Translate</button>

    <div id="translation"></div>

    <div id="error" class="error"></div>

    <script>
        const apiKey = 'YOUR_API_KEY'; // Replace with your actual API key

        const inputText = document.getElementById('inputText');
        const targetLanguage = document.getElementById('targetLanguage');
        const translateButton = document.getElementById('translateButton');
        const translationDiv = document.getElementById('translation');
        const errorDiv = document.getElementById('error');

        translateButton.addEventListener('click', translateText);

        async function translateText() {
            const text = inputText.value;
            const target = targetLanguage.value;

            if (!text) {
                errorDiv.textContent = "Please enter text to translate.";
                translationDiv.textContent = "";
                return;
            }

            errorDiv.textContent = "";
            translationDiv.textContent = "Translating...";

            try {
                const translatedText = await fetchTranslation(text, target);
                translationDiv.textContent = translatedText;
            } catch (error) {
                console.error("Translation error:", error);
                translationDiv.textContent = "";
                errorDiv.textContent = "Translation failed.  Please check your API key and network connection.";
            }
        }


        async function fetchTranslation(text, target) {
            // Using Google Translate API (Example - Replace with your preferred API)
             const url = `https://translation.googleapis.com/language/translate/v2?key=${apiKey}&q=${encodeURIComponent(text)}&target=${target}`;



            try {
                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();

                if (data.error) {
                    throw new Error(data.error.message);
                }

                return data.data.translations[0].translatedText;
            } catch (error) {
                console.error("API error:", error);
                throw error;
            }
        }

        // Alternative implementation using DeepL API (Example) - Requires DeepL Pro subscription
        // async function fetchTranslation(text, target) {
        //     const url = 'https://api.deepl.com/v2/translate';
        //     const apiKey = 'YOUR_DEEPL_API_KEY';  // Replace with your DeepL API key
        //     const body = new URLSearchParams({
        //         auth_key: apiKey,
        //         text: text,
        //         target_lang: target.toUpperCase()
        //     });

        //     try {
        //         const response = await fetch(url, {
        //             method: 'POST',
        //             body: body,
        //             headers: {
        //                 'Content-Type': 'application/x-www-form-urlencoded'
        //             }
        //         });

        //         if (!response.ok) {
        //             throw new Error(`HTTP error! status: ${response.status}`);
        //         }

        //         const data = await response.json();

        //         if (data.error) {
        //             throw new Error(data.error.message);
        //         }

        //         return data.translations[0].text;

        //     } catch (error) {
        //         console.error("API error:", error);
        //         throw error;
        //     }
        // }


        //  Real-time Implementation (Optional - Comment out the button event listener if using this)
        //  inputText.addEventListener('input', () => {
        //      debounce(translateText, 500)(); // Translate after 500ms of inactivity
        //  });

        //  function debounce(func, delay) {
        //      let timeout;
        //      return function(...args) {
        //          clearTimeout(timeout);
        //          timeout = setTimeout(() => {
        //              func.apply(this, args);
        //          }, delay);
        //      };
        //  }

    </script>
</body>
</html>
```
👁️ Viewed: 9

Comments