DEV Community

Lens
Lens

Posted on • Edited on

Making a Morse Code Translator with JS.

During the summer I decided to make a Morse Code Translator to help practice using JavaScript. I'll show how I made it by showing and explaining my code with diagrams as well.

If you want to go to it's website click here: https://morse-code-translater.vercel.app/

Quick HTML and CSS review

I decided the top would have a Morse Code title with a typing animation and in the center of the page a form with two text area's, one where the user can input, and one that'll the output. Between them I added a switch button (to go from text to morse or morse to text again) using an icon from Ionicons and a Morse code reference button using the details and summary tags. When focused, there's a translate button in the input text area (top one). Finally on the bottom is the text that shows how many secret themes you found. I used CSS variables to quickly change the theme of the websites based on whether the user's computer is on dark or light mode or if they found a special Morse code message that'll give them a secret theme.


JS Algorithm

1. Collecting User Input and checking if it's good.

To get the user's input we first have to store the elements needed, which are the textareas and the user input in them. We can grab the user input with the value property as soon as the translate button is clicked, then check if it uses dots and dashes only with the checkIfValid() function.

//storing the elements
var InputTextArea = document.getElementById("morseTextArea");
var OutputTextArea = document.getElementById("textArea");
var translateButton = document.querySelector(".translateBtn");
//storing the user input from the text area element
var input = InputTextArea.value.toString("");


function checkIfValid() {
  input = InputTextArea.value.toString("");
  if (isInputMorse && input.match(/[a-zA-Z0-9_@#$%^&*()]/g) === null) {
    morseToText();
    return console.log(input.split(" "));
  }
  if (!isInputMorse) {
    textToMorse();
    return console.log(input.split(" "));
  } else {
    InputTextArea.value = "";
  }


translateButton.addEventListener("click", checkIfValid);


Enter fullscreen mode Exit fullscreen mode

2. Morse to text or text to Morse?

To let the computer know whether we're translating morse to text or text to morse, I created a boolean variable called isInputMorse (seen being used in the example above) which starts as true. However, if the switch button is clicked then it changes to its opposite value (ex: true to false). In the checkIfVaild() function the user input must use only dots and dashes and have the isInputMorse variable set to true to translate from morse to text, but if that variable is set to false then it'll translate text to morse. The placeholders of the text areas also change based on whether the variable is true or false.

var isInputMorse = true;
var swapBtn = document.getElementById("swapBtn");

swapBtn.addEventListener("click", () => {
  isInputMorse = !isInputMorse;
  OutputTextArea.value = "";
  InputTextArea.value = "";
  if (!isInputMorse) {
    InputTextArea.setAttribute("placeholder", "Text(Input)");
    OutputTextArea.setAttribute("placeholder", "Morse(Output)");
  } else {
    InputTextArea.setAttribute("placeholder", "Morse(Input)");
    OutputTextArea.setAttribute("placeholder", "Text(Output)");
  }
});

Enter fullscreen mode Exit fullscreen mode

3. Translating

I made two functions for translating, morseToText() and textToMorse() which should be obvious as to what they do. The morse to text function splits the user input into a character-by-character array which is then mapped with the morseRef.


var morseRef = {
  ".-": "A",
  "-...": "B",
  "-.-.": "C",
  "-..": "D",
  ".": "E",
  "..-.": "F",
  "--.": "G",
  "....": "H",
  "..": "I",
  ".---": "J",
  "-.-": "K",
  ".-..": "L",
  "--": "M",
  "-.": "N",
  "---": "O",
  ".--.": "P",
  "--.-": "Q",
  ".-.": "R",
  "...": "S",
  "-": "T",
  "..-": "U",
  "...-": "V",
  ".--": "W",
  "-..-": "X",
  "-.--": "Y",
  "--..": "Z",
  ".----": "1",
  "..---": "2",
  "...--": "3",
  "....-": "4",
  ".....": "5",
  "-....": "6",
  "--...": "7",
  "---..": "8",
  "----.": "9",
  "-----": "0",
  "/": " ",
  "--..--": ",",
  "..--..": "?",
  "-.-.-.": ";",
  "---...": ":",
  "-....-": "-",
  "-..-.": "/",
  ".----.": "'",
  "-.-.--": "!",
};

function morseToText() {
    let str = input
    .split(" ")
    .map((code) => morseRef[code])
    .join("");
    OutputTextArea.value = str;
    lookForSecrets();

}
Enter fullscreen mode Exit fullscreen mode

Next the new text array is joined together and an output is given in the output text area for the user to see.

The text to morse function uses a similar method, but a reversed morseRef object. The user input goes into all caps and gets mapped with the reversed morseRef to become Morse, and then joined together again to be given as Morse code output.

var reversedMorseRef = {};

for (var key in morseRef) {
  if (morseRef.hasOwnProperty(key)) {
    reversedMorseRef[String(morseRef[key])] = key;
  }

function textToMorse() {
  let textStr = input
    .toUpperCase()
    .split("")
    .map((text) => reversedMorseRef[text])
    .join(" ");
  OutputTextArea.value = textStr;
}

Enter fullscreen mode Exit fullscreen mode

Here's a diagram I made on Figma for a more visual explanation on the functions.
Code diagram

Hints to Secrets

I also added secret themes to my website, you can get them by entering special Morse code messages.

Hints:

  1. The most common Morse code message used in emergencies
  2. A famously blinked morse code message during the Vietnam war
  3. The first morse code message ever made

That's all for now, thank you for reading!

Top comments (1)

Collapse
 
mneme profile image
Alex T

love it! It's fun to see someone make morse code with JS~ keep up with your great work!