CSS Language Translator (CSS, HTML & JAVASCRIPT)

CSS Language Translator (CSS, HTML & JAVASCRIPT)

Welcome to another tutorial on “CSS Language Translator”. In this tutorial, you will learn about creating a web application that translates text using CSS, HTML, and JavaScript. This tutorial aims to provide you with a comprehensive understanding of these languages and their integration to achieve a specific functionality.

Video: CSS Language Translator

Project Folder Structure:

Now before we move on to actual coding we create a project folder structure. We name the project folder as ”Language Translator”. Within this folder we have 3 files. These files are:

  • index.html
  • style.css
  • script.js

HTML Code

Let’s commence by incorporating the HTML code. Kindly duplicate the ensuing code and integrate it into your HTML file.

<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <title>A Language Translator</title>
    </head>
    
    <body>
        <div class="container">
            <div class="wrapper">
                <div class="text-input">
                    <textarea spellcheck="false" class="from-text" placeholder="Nijaa.com - Enter text"></textarea>
                    <ul class="controls">
                        <li class="row from">
                            <div class="icons">
                                <ion-icon id="from" name="volume-medium-outline"></ion-icon>
                                <ion-icon id="from" name="copy-outline"></ion-icon>
                            </div>
                            <select></select>
                        </li>
                        <li class="exchange">
                            <ion-icon name="swap-vertical"></ion-icon>
                        <li class="row to">
                            <select></select>
                            <div class="icons">
                                <ion-icon id="to" name="volume-medium-outline"></ion-icon>
                                <ion-icon id="to" name="copy-outline"></ion-icon>
                            </div>
                        </li>
                    </ul>
                    <textarea spellcheck="false" readonly disabled class="to-text" placeholder="Translation"></textarea>
                </div>
            </div>
            <button>Translate it</button>
        </div>
  <script src="script.js"></script>
  </body>
</html>
Code language: HTML, XML (xml)

This HTML code defines the structure for a language translator interface. It includes input and output text areas, language selection dropdowns, control buttons, and a translation trigger button. The structure is organized using container and wrapper elements for layout consistency. The interface provides functionality for entering text to translate, selecting source and target languages, and displaying the translation output. Additionally, it includes a script reference for handling translation logic.

CSS Code

Next, we embellish our game with CSS. To implement this, please duplicate the ensuing code and insert it into your stylesheet.

@import "https://fonts.googleapis.com/css2?family=Lalezar&amp;family=Poppins:wght@100;200;300;400;500;600;700;800&amp;display=swap";

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", Lalezar, cursive, sans-serif;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 10px;
  min-height: 100vh;
  background: #790000;
  padding: 3rem;
}

.container {
  max-width: 900px;
  width: 100%;
  padding: 30px;
  background: #fff;
  border-radius: 1rem;
  box-shadow: 0px 0px 36px -5px #000000;
}

.wrapper {
  border-radius: 5px;
  border: 1px solid #ccc;
}

.wrapper .text-input {
  display: block;
}

.text-input .to-text {
  border-radius: 0px;
  border-top: 1px solid #ccc;
}

.text-input textarea {
  height: 250px;
  width: 100%;
  border: none;
  outline: none;
  resize: none;
  background: none;
  font-size: 18px;
  padding: 10px 15px;
  border-radius: 0.3rem;
}

.text-input textarea::placeholder {
  color: #b7b6b6;
}

.controls,
li,
.icons,
.icons ion-icon {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.controls {
  list-style: none;
  padding: 12px 15px;
  border-top: 1px solid #ccc;
}

.controls .row .icons {
  width: 38%;
}

.controls .row .icons ion-icon {
  width: 50px;
  color: #adadad;
  font-size: 1.7rem;
  cursor: pointer;
  transition: transform 0.2s ease;
  justify-content: center;
}
.controls .row.from .icons {
  padding-right: 15px;
  border-right: 1px solid #ccc;
}
.controls .row.to .icons {
  padding-left: 15px;
  border-left: 1px solid #ccc;
}
.controls .row select {
  color: #333;
  border: none;
  outline: none;
  font-size: 18px;
  background: none;
  padding-left: 5px;
}
.text-input textarea::-webkit-scrollbar {
  width: 4px;
}
.controls .row select::-webkit-scrollbar {
  width: 8px;
}
.text-input textarea::-webkit-scrollbar-track,
.controls .row select::-webkit-scrollbar-track {
  background: #fff;
}
.text-input textarea::-webkit-scrollbar-thumb {
  background: #ddd;
  border-radius: 8px;
}
.controls .row select::-webkit-scrollbar-thumb {
  background: #999;
  border-radius: 8px;
  border-right: 2px solid #ffffff;
}
.controls .exchange {
  color: #adadad;
  cursor: pointer;
  font-size: 1.7rem;
  transition: transform 0.2s ease;
}
.controls ion-icon:active {
  transform: scale(0.9);
}
.container button {
  width: 100%;
  padding: 14px;
  outline: none;
  border: none;
  color: #fff;
  cursor: pointer;
  margin-top: 20px;
  font-size: 1.2rem;
  border-radius: 0.3rem;
  background: #410101;
  border-radius: 20px;
}

@media (max-width: 660px) {
  .container {
    padding: 20px;
  }
  .wrapper .text-input {
    flex-direction: column;
  }
  .text-input .to-text {
    border-left: 0px;
    border-top: 1px solid #ccc;
  }
  .text-input textarea {
    height: 200px;
  }
  .controls .row .icons {
    display: inline-flex;
    flex-direction: column;
  }
  .container button {
    padding: 13px;
    font-size: 1.2rem;
  }
  .controls .row select {
    font-size: 1.2rem;
  }
  .controls .exchange {
    font-size: 1.2rem;
  }
}
@media screen and (max-width: 1250px) {
  .container {
    zoom: 0.7;
  }
}
Code language: CSS (css)

This CSS code styles a language translation interface. It sets up fonts, layout, and styling for various elements such as text areas, controls, and buttons. Additionally, it includes media queries to ensure responsiveness on different screen sizes.

CSS Code Explanation

  1. The code starts by importing a Google Fonts stylesheet, which provides the “Lalezar” and “Poppins” fonts. These fonts are then used throughout the application.
  2. The CSS * selector is used to set some global styles for the entire application, such as setting the padding, margin, and box-sizing properties. It also defines the default font-family to be used.
  3. The body element is styled to center its content both horizontally and vertically. It also sets a background color, adds some padding, and sets a minimum height for the page.
  4. A container div is created to hold the main content of the application. It has a maximum width, a fixed width, padding, and a border-radius for a rounded appearance. Additionally, a box-shadow is added for depth.
  5. The wrapper div is used to hold the input fields and the controls. It has a border-radius and a border for a more defined appearance.
  6. The text-input class is used to style the input fields. It sets the display property to block and adds some padding and a font-size. The to-text class is used to remove the bottom border-radius and add a top border to differentiate it from the from-text input.
  7. The textarea element within the text-input class is styled to have a specific height, width, border, outline, resize, background, font-size, and padding. It also sets the placeholder color.
  8. The controls class is used to style the list of controls, such as the exchange icon and select tags. It also sets the display property to flex for better alignment.
  9. The icons class is used to style the icons within the controls. It aligns the items, sets the color, font-size, cursor, and adds a transform property for a hover effect. The from and to classes are used to adjust the padding and borders for better organization.
  10. The button element is styled to have a width of 100%, padding, outline, border, color, cursor, margin-top, font-size, and background color. It also has a border-radius for a rounded appearance.
  11. The media queries in the code adjust the layout and styling for different screen sizes. The first media query (max-width: 660px) changes the layout for smaller screens by stacking the input fields vertically, adjusting the padding, font-size, and border-radius of certain elements. The second media query (screen and max-width: 1250px) reduces the size of the container by using the zoom property.

JS Code

Finally, we add functionality using Javascript. For this once again copy the code below and paste it into your script file.

const languages = {
    "am-ET": "Amharic",
    "ar-SA": "Arabic",
    "be-BY": "Bielarus",
    "bem-ZM": "Bemba",
    "bi-VU": "Bislama",
    "bjs-BB": "Bajan",
    "bn-IN": "Bengali",
    "bo-CN": "Tibetan",
    "br-FR": "Breton",
    "bs-BA": "Bosnian",
    "ca-ES": "Catalan",
    "cop-EG": "Coptic",
    "cs-CZ": "Czech",
    "cy-GB": "Welsh",
    "da-DK": "Danish",
    "dz-BT": "Dzongkha",
    "de-DE": "German",
    "dv-MV": "Maldivian",
    "el-GR": "Greek",
    "en-GB": "English",
    "es-ES": "Spanish",
    "et-EE": "Estonian",
    "eu-ES": "Basque",
    "fa-IR": "Persian",
    "fi-FI": "Finnish",
    "fn-FNG": "Fanagalo",
    "fo-FO": "Faroese",
    "fr-FR": "French",
    "gl-ES": "Galician",
    "gu-IN": "Gujarati",
    "ha-NE": "Hausa",
    "he-IL": "Hebrew",
    "hi-IN": "Hindi",
    "hr-HR": "Croatian",
    "hu-HU": "Hungarian",
    "id-ID": "Indonesian",
    "is-IS": "Icelandic",
    "it-IT": "Italian",
    "ja-JP": "Japanese",
    "kk-KZ": "Kazakh",
    "km-KM": "Khmer",
    "kn-IN": "Kannada",
    "ko-KR": "Korean",
    "ku-TR": "Kurdish",
    "ky-KG": "Kyrgyz",
    "la-VA": "Latin",
    "lo-LA": "Lao",
    "lv-LV": "Latvian",
    "men-SL": "Mende",
    "mg-MG": "Malagasy",
    "mi-NZ": "Maori",
    "ms-MY": "Malay",
    "mt-MT": "Maltese",
    "my-MM": "Burmese",
    "ne-NP": "Nepali",
    "niu-NU": "Niuean",
    "nl-NL": "Dutch",
    "no-NO": "Norwegian",
    "ny-MW": "Nyanja",
    "ur-PK": "Pakistani",
    "pau-PW": "Palauan",
    "pa-IN": "Panjabi",
    "ps-PK": "Pashto",
    "pis-SB": "Pijin",
    "pl-PL": "Polish",
    "pt-PT": "Portuguese",
    "rn-BI": "Kirundi",
    "ro-RO": "Romanian",
    "ru-RU": "Russian",
    "sg-CF": "Sango",
    "si-LK": "Sinhala",
    "sk-SK": "Slovak",
    "sm-WS": "Samoan",
    "sn-ZW": "Shona",
    "so-SO": "Somali",
    "sq-AL": "Albanian",
    "sr-RS": "Serbian",
    "sv-SE": "Swedish",
    "sw-SZ": "Swahili",
    "ta-LK": "Tamil",
    "te-IN": "Telugu",
    "tet-TL": "Tetum",
    "tg-TJ": "Tajik",
    "th-TH": "Thai",
    "ti-TI": "Tigrinya",
    "tk-TM": "Turkmen",
    "tl-PH": "Tagalog",
    "tn-BW": "Tswana",
    "to-TO": "Tongan",
    "tr-TR": "Turkish",
    "uk-UA": "Ukrainian",
    "uz-UZ": "Uzbek",
    "vi-VN": "Vietnamese",
    "wo-SN": "Wolof",
    "xh-ZA": "Xhosa",
    "yi-YD": "Yiddish",
    "zu-ZA": "Zulu",
  };
  
  const fromText = document.querySelector(".from-text"),
    toText = document.querySelector(".to-text"),
    exchageIcon = document.querySelector(".exchange"),
    selectTag = document.querySelectorAll("select"),
    icons = document.querySelectorAll(".row ion-icon");
  (translateBtn = document.querySelector("button")),
    selectTag.forEach((tag, id) => {
      for (let lang_code in languages) {
        let selected =
          id == 0
            ? lang_code == "en-GB"
              ? "selected"
              : ""
            : lang_code == "fa-IR"
            ? "selected"
            : "";
        let option = `<option ${selected} value="${lang_code}">${languages[lang_code]}</option>`;
        tag.insertAdjacentHTML("beforeend", option);
      }
    });
  
  fromText.addEventListener("keyup", () => {
    if (!fromText.value) {
      toText.value = "";
    }
  });
  
  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");
      });
  });
  
  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;
  });
  
  icons.forEach((icon) => {
    icon.addEventListener("click", ({ target }) => {
      if (!fromText.value || !toText.value) return;
      if (target.getAttribute("name") == "copy-outline") {
        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);
      }
    });
  });
Code language: JavaScript (javascript)

This JavaScript code sets up functionality for a language translation interface. It populates the language dropdowns, handles translation requests, enables language exchange, and provides options to copy and speak text using the Web Speech API.

JavaScript Code Explanation

  1. The code starts by defining an object called “languages” which contains language codes and their respective names.
  2. Next, it selects various elements from the HTML document using their class names or IDs. These elements include text input fields, select tags, and icons.
  3. The code then populates the select tags with language options based on the “languages” object.
  4. An event listener is added to the text input field for translating text. When the user types something in the input field, the code checks if it’s empty. If it is, the translated text box is cleared.
  5. When the user clicks the translate button, the code retrieves the text, the selected languages for translation (source and target), and sends a request to an online translation API (https://api.mymemory.translated.net/get).
  6. The API response is then processed to extract the translated text and updates the translated text input field.
  7. An event listener is added to the exchange icon. When clicked, it swaps the text and selected languages between the source and target fields.
    • Each icon in the row is assigned an event listener. If the icon is clicked, the code checks if there’s text in both input fields. If there is, it performs one of two actions:

    • if the clicked icon has an attribute “name” equal to “copy-outline”, it copies the text from the corresponding input field to the clipboard.
  8. If the clicked icon has a different “name” attribute, it uses the Web Speech API to speak the text from the corresponding input field in the selected language.
  9. The code also enables users to exchange the source and target languages with a single click, making the translation process more convenient.
  10. By using an online translation API, the code leverages the power of advanced language processing algorithms to provide accurate translations. This ensures that the translated text maintains its meaning and context from the original text.
  11. The Web Speech API is utilized to enable text-to-speech functionality, allowing users to hear the translated text in the selected language. This feature can be helpful for users who prefer listening to the text or for those with visual impairments.
  12. The code is well-structured, with clear variable and function names, making it easier for other developers to understand and modify the code if needed.
  13. The use of event listeners ensures that the application responds to user interactions in real-time, providing a smooth and responsive user experience.
  14. The code also handles some error cases, such as when the user tries to translate an empty text or when the necessary fields are empty for the copy or speech actions.

Leave a Reply

Your email address will not be published. Required fields are marked *