create a simple language translator in HTML, you can use HTML and JavaScript

Admin
0
To create a simple language translator in HTML, you can use HTML and JavaScript. Here’s a basic example using Google Translate's API:

HTML Code for Language Translator

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Language Translator</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            flex-direction: column;
        }
        textarea {
            width: 300px;
            height: 100px;
            margin: 10px;
            padding: 10px;
            font-size: 16px;
        }
        select, button {
            padding: 10px;
            font-size: 16px;
            margin: 5px;
        }
    </style>
</head>
<body>

    <h1>Language Translator</h1>
    <textarea id="inputText" placeholder="Enter text here"></textarea>
    <select id="language">
        <option value="es">Spanish</option>
        <option value="fr">French</option>
        <option value="de">German</option>
        <option value="hi">Hindi</option>
        <!-- Add more languages as needed -->
    </select>
    <button onclick="translateText()">Translate</button>
    <textarea id="outputText" readonly placeholder="Translation appears here"></textarea>

    <script>
        function translateText() {
            const text = document.getElementById("inputText").value;
            const language = document.getElementById("language").value;

            fetch(`https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=${language}&dt=t&q=${encodeURIComponent(text)}`)
                .then(response => response.json())
                .then(data => {
                    document.getElementById("outputText").value = data[0][0][0];
                })
                .catch(error => {
                    document.getElementById("outputText").value = "Error translating text";
                    console.error(error);
                });
        }
    </script>

</body>
</html>

Explanation

HTML Structure: There are two text areas (inputText for the original text and outputText for the translation).

Select Dropdown: Allows you to choose the target language.

JavaScript Function: Fetches translation from Google Translate's unofficial API endpoint using fetch for simplicity.


Important Note

The above example uses an unofficial Google Translate endpoint, which may be limited or restricted. For production applications, consider using an official translation API like Google Cloud Translation API or Microsoft Translator API.

Post a Comment

0 Comments
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Ok, Go it!