Simple Language Translator with API
Day 8 of #100daysofMiva coding challenge and I worked on a simple translator model that translates a language to another ?
It's JS, it's magic✨?
? Language Translator Script Documentation
Overview
This JavaScript code is designed to create a playful, interactive language translator! It utilizes the MyMemory API to translate text between different languages and allows you to swap languages, copy translations, or even have the text spoken aloud. ??
Features
- ? Language Selection: Users can choose from a wide array of languages, ranging from Amharic to Zulu!
- ? Language Swap: Easily swap between the source and target languages with a click of a button.
- ? Text-to-Speech: Listen to the original or translated text in the selected language.
- ? Copy to Clipboard: Copy the original or translated text with a single click.
Code Breakdown
Language Data
const countries = { /*...*/ }
This object contains the available languages and their respective country codes. For example, "en-GB": "English" pairs the language code with its name.
Dynamic Dropdowns
selectTag.forEach((tag, id) => { /*...*/ });
This code dynamically populates the dropdown menus with all the languages listed in the countries object. The first dropdown defaults to English ("en-GB"), and the second to Hindi ("hi-IN").
Language Swap
exchageIcon.addEventListener("click", () => { /*...*/ });
Clicking the swap icon allows users to swap the text and selected languages between the "from" and "to" fields.
Real-Time Translation
translateBtn.addEventListener("click", () => { /*...*/ });
When the "Translate" button is clicked, the text is sent to the MyMemory API, and the translated text is displayed in the "to-text" field. While waiting for the response, a "Translating..." placeholder is shown.
Text-to-Speech & Copy
icons.forEach(icon => { /*...*/ });
This section handles the Text-to-Speech and copy functionalities:
- Speech: Plays the text aloud in the selected language.
- Copy: Copies the text to the clipboard.
How It Works
- Select Languages ?: Choose your languages from the dropdowns.
- Type or Paste Text ✍️: Input the text you want to translate.
- Translate ?: Click the "Translate" button and watch the magic happen!
- Swap, Listen, or Copy ???: Swap languages, listen to the translation, or copy the text to your clipboard.
Dependencies
- MyMemory API: The translation functionality is powered by the MyMemory API. Ensure you have an active internet connection for it to work.
Potential Enhancements
- Language Auto-Detection: Automatically detect the language of the input text.
- Advanced Error Handling: Improve the response for translation errors or API failures.
- Multiple Translations: Show alternative translations where available.
Here’s a step-by-step breakdown of how the code works and what it does:
Step 1: Defining Available Languages
const countries = { /*...*/ }
- What it does: This object contains key-value pairs where the key is a language-country code (like "en-GB" for English) and the value is the name of the language (like "English").
- Purpose: This data is used to populate the language selection dropdowns so users can choose their source and target languages.
Step 2: Selecting DOM Elements
const fromText = document.querySelector(".from-text"), toText = document.querySelector(".to-text"), exchageIcon = document.querySelector(".exchange"), selectTag = document.querySelectorAll("select"), icons = document.querySelectorAll(".row i"); translateBtn = document.querySelector("button"),
-
What it does: This code selects various elements from the HTML document and stores them in variables for easy access later.
- fromText and toText: Text areas where users input text and see the translation.
- exchageIcon: The icon used to swap languages and text.
- selectTag: The dropdown menus for selecting languages.
- icons: Icons for copy and speech functions.
- translateBtn: The button that triggers the translation.
Step 3: Populating Language Dropdowns
selectTag.forEach((tag, id) => { for (let country_code in countries) { let selected = id == 0 ? country_code == "en-GB" ? "selected" : "" : country_code == "hi-IN" ? "selected" : ""; let option = `<option ${selected} value="${country_code}">${countries[country_code]}</option>`; tag.insertAdjacentHTML("beforeend", option); } });
-
What it does: This loop goes through the countries object and adds each language as an option in the language selection dropdowns.
- If the dropdown is the first one (id == 0), English ("en-GB") is selected by default.
- If the dropdown is the second one (id == 1), Hindi ("hi-IN") is selected by default.
Step 4: Swapping Languages and Text
exchageIcon.addEventListener("click", () => { let tempText = fromText.value, tempLang = selectTag[0].value; fromText.value = toText.value; toText.value = tempText; selectTag[0].value = selectTag[1].value; selectTag[1].value = tempLang; });
-
What it does: When the swap icon is clicked, this function swaps the text between the "from" and "to" text areas as well as the selected languages.
- tempText temporarily holds the original text from the "from-text" field.
- tempLang temporarily holds the original language from the first dropdown.
- The "from-text" is then replaced with the "to-text", and vice versa. The selected languages are also swapped.
Step 5: Clearing Translated Text
fromText.addEventListener("keyup", () => { if(!fromText.value) { toText.value = ""; } });
- What it does: If the user deletes all the text from the "from-text" field, this function automatically clears the "to-text" field as well.
- Purpose: Ensures that if the input text is cleared, the translation is cleared too, preventing confusion.
Step 6: Translating Text
translateBtn.addEventListener("click", () => { let text = fromText.value.trim(), translateFrom = selectTag[0].value, translateTo = selectTag[1].value; if(!text) return; toText.setAttribute("placeholder", "Translating..."); let apiUrl = `https://api.mymemory.translated.net/get?q=${text}&langpair=${translateFrom}|${translateTo}`; fetch(apiUrl).then(res => res.json()).then(data => { toText.value = data.responseData.translatedText; data.matches.forEach(data => { if(data.id === 0) { toText.value = data.translation; } }); toText.setAttribute("placeholder", "Translation"); }); });
-
What it does: When the "Translate" button is clicked, this function:
- Extracts the text from the "from-text" field.
- Identifies the selected languages from the dropdowns.
- Sends a request to the MyMemory API with the text and selected languages.
- Receives the translation from the API and displays it in the "to-text" field.
- Updates the placeholder text while waiting for the translation to indicate that the process is ongoing.
Summary
The script allows users to translate text between different languages with a dynamic and interactive interface. Users can select languages, type in their text, translate it with a click, swap languages and text, hear the translation spoken aloud, or copy it to their clipboard.
Enjoy playing with different languages and make your translation journey fun and interactive! ?? Unto the next ?✌?✨
Check it out here
https://app.marvelly.com.ng/100daysofMiva/day-8/
Source code
https://github.com/Marvellye/100daysofMiva/blob/main/Projects%2FDay_8-Simple_language_translator
The above is the detailed content of Simple Language Translator with API. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.
