Open In App

Javascript Program to Build a Morse Code Converter

Last Updated : 28 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will create a Morse Code Translator app using HTML, CSS, and JavaScript. Morse code, a syste­m of encoding text characters into dot and dash se­quences. The app’s functionality includes the ability to translate Morse­ code into text format.

Output Preview:

Build-a-Morse-Code-Converter-Using-Javascript

Approach

The Morse­ Code Translator web application combines HTML, CSS, and JavaScript code­ to create a visually appealing inte­rface. It offers two sections for translation: Morse­ Code to Text and Text to Morse­ Code. Users can convenie­ntly input their text in the corre­sponding fields and utilize the “Translate­” buttons to convert it betwee­n Morse code and plain text.

  • HTML code cre­ates a webpage for conve­rting Morse Code. It includes me­tadata, styling options, and two sections for translation.
  • This CSS code is re­sponsible for styling a Morse Code Conve­rter application. It defines the­ font, background color, and margins for the entire page­.
  • The JavaScript code­ comprises multiple functions that work togethe­r for the Morse Code­ Converter application. Firstly, the ge­nerateMorseCode­() function creates a dictionary mapping characters to the­ir respective Morse­ code represe­ntations.

Project Structure

InfiniteScroll

Project Structure

Example: Below is the implementation of the project.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <title>Morse Code Converter</title>
    <link rel="stylesheet" href="style.css">
</head>
  
<body>
    <div class="container">
        <h1 class="title">Morse Code Translator</h1>
        <div class="input-container">
            <label class="label">Text to Morse Code:</label>
            <textarea class="input" 
                id="textToMorse" rows="4"></textarea>
            <button 
                onclick="handleTextToMorseTranslate()" 
                    class="btn">Translate</button>
            <p class="result">Translation:
                <span id="textToMorseOutput"></span>
                <button class="btn" 
                    onclick=
                        "copyTextToMorseOutput()">Copy</button>
            </p>
            <p class="success-message" 
               id="textToMorseSuccessMessage"></p>
        </div>
        <div class="input-container">
            <label class="label">
              Morse Code to Text:
              </label>
            <textarea class="input"
                      id="morseToText" rows="4">
              </textarea>
            <button onclick="handleMorseToTextTranslate()" 
                class="btn">Translate
              </button>
            <p class="result">Translation: 
                <span id="morseToTextOutput"></span>
                <button class="btn" 
                        onclick="copyMorseToTextOutput()">Copy
                  </button>
            </p>
            <p class="success-message" 
               id="morseToTextSuccessMessage">
              </p>
        </div>
    </div>
    <script src="script.js">  </script>
</body>
  
</html>


CSS




body {
    font-family: Arial, sans-serif;
    background-color: #f5f5f5;
    margin: 3rem;
    padding: 0;
  
}
  
.container {
    background-color: #fff;
    border-radius: 20px;
    box-shadow: 0 0 40px 0px rgba(0, 0, 0, 0.1);
    padding: 40px;
    margin: 20px;
    max-width: 700px;
    margin: 0 auto;
    text-align: center;
}
  
.title {
    font-size: 28px;
    margin-bottom: 20px;
    color: green;
}
  
.input-container {
    margin-bottom: 30px;
    text-align: left;
}
  
.label {
    font-size: 20px;
    color: #333;
    margin: 10px;
    font-weight: bold;
}
  
.input {
    resize: none;
    border: 1px solid black;
    border-radius: 10px;
    padding: 20px;
    margin: 10px;
    width: 90%;
}
  
.result {
    font-size: 18px;
    margin-top: 10px;
    color: #333;
    margin: 10px;
    font-family: 'Courier New', Courier, monospace;
    font-weight: bold;
}
  
.btn {
    background-color: #5272ee;
    color: #ffffff;
    border: none;
    padding: 13px;
    border-radius: 10px;
    outline: none;
    cursor: pointer;
    box-shadow: 0 0 10px 0px grey;
    margin: 5px;
}
  
.btn:hover {
    background-color: #0056b3;
}
  
.success-message {
    color: green;
    margin-top: 10px;
    font-weight: bold;
    font-family: cursive;
}


Javascript




// script.js
function generateMorseCode() {
    const code = {};
    const letters =
        'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?\'!/()&:;=+-_"$@ ';
  
    const morseValues =
        [
            '.-', '-...', '-.-.', '-..', '.', '..-.',
            '--.', '....', '..', '.---',
            '-.-', '.-..', '--', '-.', '---',
            '.--.', '--.-', '.-.', '...', '-',
            '..-', '...-', '.--', '-..-', '-.--',
            '--..', '-----', '.----', '..---',
            '...--', '....-', '.....', '-....',
            '--...', '---..', '----.', '.-.-.-',
            '--..--', '..--..', '.----.', '-.-.--',
            '-..-.', '-.--.', '-.--.-',
            '.-...', '---...', '-.-.-.', '-...-',
            '.-.-.', '-....-', '..--.-',
            '.-..-.', '...-..-', '.--.-.'
        ];
  
    for (let i = 0; i < letters.length; i++) {
        code[letters[i]] = morseValues[i];
    }
  
    return code;
}
  
const morseCode = generateMorseCode();
  
// Create reverse Morse code dictionary
const reverseMorseCode = {};
for (const key in morseCode) {
    if (morseCode.hasOwnProperty(key)) {
        const value = morseCode[key];
        reverseMorseCode[value] = key;
    }
}
  
// Function to translate text to Morse code
const translateTextToMorse = (text) => {
    const words = text.split(' ');
    const translatedWords =
        words.map((word) => {
            const chars = word.split('');
            const morseChars = chars.map((char) => {
                return morseCode[char] || char;
            });
            return morseChars.join(' ');
        });
    return translatedWords.join('/');
};
  
// Function to translate Morse code to text
const translateMorseToText = (morseText) => {
    const morseWords = morseText.split('/');
    const translatedWords =
        morseWords.map((morseWord) => {
            const morseChars = morseWord.split(' ');
            return morseChars
                .map((morseChar) => {
                    return reverseMorseCode[morseChar]
                        || morseChar;
                })
                .join('');
        });
    return translatedWords.join(' ');
};
  
// Function to handle translation from Morse code to text
const handleMorseToTextTranslate = () => {
    const morseToText =
        document.getElementById('morseToText')
            .value.trim().toUpperCase();
  
    if (morseToText === '') {
        document.getElementById('morseToTextOutput')
            .textContent = 'No Input Provided';
        return;
    }
  
    const translatedText =
        translateMorseToText(morseToText);
    document.getElementById('morseToTextOutput')
        .textContent = translatedText;
};
  
// Function to handle translation from text to Morse code
const handleTextToMorseTranslate = () => {
    const textToMorse =
        document.getElementById('textToMorse')
            .value.trim().toUpperCase();
  
    if (textToMorse === '') {
        document.getElementById('textToMorseOutput')
            .textContent = 'No Input Provided';
        return;
    }
  
    const translatedMorse =
        translateTextToMorse(textToMorse);
    document.getElementById('textToMorseOutput')
        .textContent = translatedMorse;
};
  
  
// Function to show success message
const showSuccessMessage =
    (elementId, message) => {
        const successMessage =
            document.getElementById(elementId);
        successMessage.textContent = message;
        setTimeout(() => {
            successMessage.textContent = '';
        }, 2000); // Clear the message after 2 seconds
    };
  
// Function to copy Morse To Text output
const copyMorseToTextOutput = () => {
    const morseToTextOutput =
        document.getElementById('morseToTextOutput');
    const text =
        morseToTextOutput.textContent;
    copyTextToClipboard(text);
    showSuccessMessage('morseToTextSuccessMessage',
        'Copied to Clipboard!!');
};
  
// Function to copy Text To Morse output
const copyTextToMorseOutput = () => {
    const textToMorseOutput =
        document.getElementById('textToMorseOutput');
    const text =
        textToMorseOutput.textContent;
    copyTextToClipboard(text);
    showSuccessMessage('textToMorseSuccessMessage',
        'Copied to Clipboard!!');
};
  
// Function to copy text to clipboard
const copyTextToClipboard = (text) => {
    const textArea =
        document.createElement("textarea");
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.select();
    document.execCommand('copy');
    document.body.removeChild(textArea);
};


Output:
Build-a-Morse-Code-Converter-Using-Javascript



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads