Open In App

Design a Unit Converter using HTML CSS and JavaScript

Last Updated : 16 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will be developing an interactive and styled unit converter using HTML, CSS, and JavaScript.In this application, we have a select category option box in which different types of units are specified, like temperature, area, weight, length, and time. As per the user selection, the associated fields with the input fields are displayed.

Preview of final output: Let us have a look at how the final output will look like.

Screenshot-2023-10-17-at-19-02-30-GFG-Converter

Prerequisites

Approach to create Unit Converter

  • Create the HTML structure with the headings, subheadings, option boxes, form inputs, and buttons using different HTML tags like <h1>, <h3>, <button>, etc.
  • Once we have created the HTML structure or layout, we need to add attractive CSS by applying the CSS properties to it. We can give colors, transitions, and hovering to the elements of the application.
  • In the main JS code, we need to define the overall behavior of the application. Firstly, we are rendering the input forms as per the user selection from the option box. Then, for each of the buttons, we are adding the event listener.
  • Suppose the temperature option is selected by the user. The temperature form will be opened with the custom input fields. We have defined the functions for each unit, like tempFn(), areaFn(), weightFn(), lengthFn(), and timeFn(). All these functions consist of the unit conversion code with its respective conversion logic and formulas.

 

Example: This example describes the basic implementation of the Unit Converter using HTML CSS & JavaScript.

Javascript




let inputforms =
    document.querySelectorAll(
        ".conversion");
inputforms.forEach(
    (form) =>
        (form.style.display = "none"));
let category = document.getElementById(
    "conversionCategory");
category.addEventListener(
    "change",
    function () {
        let userInput = category.value;
        inputforms.forEach(
            (form) =>
                (form.style.display =
                    "none"));
        document.getElementById(
            userInput)
            .style.display = "block";});
document
    .getElementById(
        "temperatureConvertBtn")
    .addEventListener("click", tempFn);
document
    .getElementById("areaConvertBtn")
    .addEventListener("click", areaFn);
document
    .getElementById("weightConvertBtn")
    .addEventListener(
        "click",
        weightFn);
document
    .getElementById("lengthConvertBtn")
    .addEventListener(
        "click",
        lengthFn);
document
    .getElementById("timeConvertBtn")
    .addEventListener("click", timeFn);
function tempFn() {
    let valInput = parseFloat(
        document.getElementById(
            "temperatureInput"
        ).value);
    let fromUnit =
        document.getElementById(
            "fromTemperatureUnit").value;
    let toUnit =
        document.getElementById(
            "toTemperatureUnit").value;
    let result;
    if (fromUnit === "celsius" &&
        toUnit === "fahrenheit") {
        result =
            (valInput * 9) / 5 + 32;} 
    else if (fromUnit === "celsius" &&
             toUnit === "kelvin") {
        result = valInput + 273.15;} 
    else if (fromUnit === "fahrenheit" &&
             toUnit === "celsius") {
        result =
            ((valInput - 32) * 5) / 9;} 
    else if (fromUnit === "fahrenheit" &&
             toUnit === "kelvin") {
        result =
            ((valInput - 32) * 5) / 9 +
            273.15;} 
    else if (fromUnit === "kelvin" &&
             toUnit === "celsius") {
        result = valInput - 273.15;} 
    else if (fromUnit === "kelvin" &&
             toUnit === "fahrenheit") {
        result =
            ((valInput - 273.15) * 9) /
                5 +
            32;} 
    else {
        result = valInput;}
    document.getElementById(
        "temperatureResult"
    ).textContent = `Result: ${result.toFixed(
        2
)}`;}
  
function areaFn() {
    let valInput = parseFloat(
        document.getElementById(
            "areaInput"
        ).value);
    let fromUnit =
        document.getElementById(
            "fromAreaUnit").value;
    let toUnit =
        document.getElementById(
            "toAreaUnit").value;
    let conversionFactors = {
        sqMeter: 1,
        sqKilometer: 0.000001,
        sqCentimeter: 10000,
        sqMillimeter: 1000000,
        acre: 0.000247105,
        hectare: 0.0001,
        sqMile: 3.861e-7,
        sqYard: 1.19599,
        sqFoot: 10.7639,
        sqInch: 1550.0031,};
    let result =
        valInput *
        (conversionFactors[toUnit] /
            conversionFactors[
                fromUnit]);
    document.getElementById(
        "areaResult")
        .textContent = `Result: ${result.toFixed(2
    )} ${toUnit}`;}
  
function weightFn() {
    let valInput = parseFloat(
        document.getElementById(
            "weightInput").value);
    let fromUnit =
        document.getElementById(
            "fromWeightUnit").value;
    let toUnit =
        document.getElementById(
            "toWeightUnit").value;
    let conversionFactors = {
        gram: 1,
        kilogram: 0.001,
        milligram: 1000,
        metricTon: 0.000001,
        longTon: 0.000984207,
        shortTon: 0.00110231,
        pound: 0.00220462,
        ounce: 0.03527396,
        carat: 5,};
    let result =
        valInput *
        (conversionFactors[toUnit] /
            conversionFactors[
                fromUnit]);
    document.getElementById(
        "weightResult"
    ).textContent = `Result: ${result.toFixed(2
    )} ${toUnit}`;
}
  
function lengthFn() {
    let valInput = parseFloat(
        document.getElementById(
            "lengthInput"
        ).value);
    let fromUnit =
        document.getElementById(
            "fromLengthUnit").value;
    let toUnit =
        document.getElementById(
            "toLengthUnit").value;
    let conversionFactors = {
        meter: 1,
        kilometer: 0.001,
        centimeter: 100,
        millimeter: 1000,
        mile: 0.000621371,
        yard: 1.09361,
        foot: 3.28084,
        inch: 39.3701,};
    let result =
        valInput *
        (conversionFactors[toUnit] /
            conversionFactors[
                fromUnit]);
    document.getElementById(
        "lengthResult")
        .textContent = `Result: 
        ${result.toFixed(2)} ${toUnit}`;}
  
function timeFn() {
    let valInput = parseFloat(
        document.getElementById(
            "timeInput").value);
    let fromUnit =
        document.getElementById(
            "fromTimeUnit").value;
    let toUnit =
        document.getElementById(
            "toTimeUnit").value;
    let conversionFactors = {
        second: 1,
        millisecond: 1000,
        minute: 1 / 60,
        hour: 1 / 3600,
        day: 1 / 86400,
        week: 1 / 604800,
        month: 1 / 2628000,
        year: 1 / 31536000,};
    let result =
        valInput *
        (conversionFactors[toUnit] /
            conversionFactors[
                fromUnit]);
    document.getElementById(
        "timeResult"
    ).textContent = `Result: ${result.toFixed(
        2
    )} ${toUnit}`;
}


HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
    <title>GFG Converter</title>
    <link rel="stylesheet" href="./styles.css">
</head>
  
<body>
    <div class="main">
        <h1 class="title">GeeksforGeeks</h1>
        <h2>Unit Converter using 
              HTML CSS and JavaScript
          </h2>
        <h5 class="subtitle">Select Category</h5>
        <select id="conversionCategory" 
                class="select-category">
            <option value="">
                - Select -
              </option>
            <option value="temperature">
                Temperature
              </option>
            <option value="area">
                Area
              </option>
            <option value="weight">
                  Weight
              </option>
            <option value="length">
                  Length
              </option>
            <option value="time">
                  Time
              </option>
        </select>
        <div class="container">
            <div class="conversion" 
                 id="temperature">
                <h2 class="category-title">
                      Temperature
                  </h2>
                <input type="number" 
                       id="temperatureInput" 
                       class="input" 
                       placeholder="Enter value">
                <select id="fromTemperatureUnit" 
                        class="unit-select">
                    <option value="celsius">
                          Celsius
                      </option>
                    <option value="kelvin">
                          Kelvin
                      </option>
                    <option value="fahrenheit">
                          Fahrenheit
                      </option>
                </select>
                <span class="arrow">âž¡</span>
                <select id="toTemperatureUnit" 
                        class="unit-select">
                    <option value="celsius">
                          Celsius
                      </option>
                    <option value="kelvin">
                          Kelvin
                      </option>
                    <option value="fahrenheit">
                          Fahrenheit
                      </option>
                </select>
                <button id="temperatureConvertBtn" 
                        class="convert-button">
                       Convert
                  </button>
                <div class="result">
                    <p id="temperatureResult">
                        Result will be 
                          displayed here
                      </p>
                </div>
            </div>
            <div class="conversion" 
                 id="area">
                <h2 class="category-title">
                      Area
                  </h2>
                <input type="number" 
                       id="areaInput" 
                       class="input" 
                       placeholder="Enter value">
                <select id="fromAreaUnit" 
                        class="unit-select">
                    <option value="sqMeter">
                          Square Meter
                      </option>
                    <option value="sqKilometer">
                          Square Kilometer
                      </option>
 <!-- Add more area units here -->
                </select>
                <span class="arrow">âž¡</span>
                <select id="toAreaUnit" 
                        class="unit-select">
                    <option value="sqMeter">
                          Square Meter
                      </option>
                    <option value="sqKilometer">
                          Square Kilometer
                      </option>
                </select>
                <button id="areaConvertBtn" 
                        class="convert-button">
                      Convert
                  </button>
                <div class="result">
                    <p id="areaResult">
                        Result will be 
                        displayed here
                  </p>
                </div>
            </div>
            <div class="conversion" id="weight">
                <h2 class="category-title">
                      Weight
                  </h2>
                <input type="number" 
                       id="weightInput" 
                       class="input" 
                       placeholder="Enter value">
                <select id="fromWeightUnit" 
                        class="unit-select">
                    <option value="gram">
                          Gram
                      </option>
                    <option value="kilogram">
                          Kilogram
                      </option>
                </select>
                <span class="arrow">âž¡</span>
                <select id="toWeightUnit" 
                        class="unit-select">
                    <option value="gram">
                           Gram
                      </option>
                    <option value="kilogram">
                        Kilogram
                      </option>
                </select>
                <button id="weightConvertBtn" 
                        class="convert-button">
                    Convert
                  </button>
                <div class="result">
                    <p id="weightResult">
                        Result will be 
                        displayed here
                      </p>
                </div>
            </div>
            <div class="conversion" id="length">
                <h2 class="category-title">
                    Length
                </h2>
                <input type="number" 
                       id="lengthInput" 
                       class="input" 
                       placeholder="Enter value">
                <select id="fromLengthUnit" 
                        class="unit-select">
                    <option value="meter">
                        Meter
                    </option>
                    <option value="kilometer">
                        Kilometer
                    </option>
                </select>
                <span class="arrow">âž¡</span>
                <select id="toLengthUnit" 
                        class="unit-select">
                    <option value="meter">
                        Meter
                    </option>
                    <option value="kilometer">
                        Kilometer
                    </option>
                </select>
                <button id="lengthConvertBtn" 
                        class="convert-button">
                    Convert
                </button>
                <div class="result">
                    <p id="lengthResult">
                        Result will be 
                        displayed here
                  </p>
                </div>
            </div>
            <div class="conversion" id="time">
                <h2 class="category-title">
                    Time
                </h2>
                <input type="number" 
                       id="timeInput" 
                       class="input" 
                       placeholder="Enter value">
                <select id="fromTimeUnit" 
                        class="unit-select">
                    <option value="second">
                        Second
                    </option>
                    <option value="minute">
                        Minute
                    </option>
                </select>
                <span class="arrow">âž¡</span>
                <select id="toTimeUnit" 
                        class="unit-select">
                    <option value="second">
                        Second
                    </option>
                    <option value="minute">
                        Minute
                    </option>
                </select>
                <button id="timeConvertBtn" 
                        class="convert-button">
                    Convert
                </button>
                <div class="result">
                    <p id="timeResult">
                        Result will be 
                        displayed here
                  </p>
                </div>
            </div>
        </div>
    </div>
    <script src="./script.js"></script>
</body>
  
</html>


CSS




body {
    background-image: linear-gradient(
        #fff48c,
        #b9a9fd
    );
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
    font-family: "Arial", sans-serif;
    overflow: hidden;
}
.main {
    background: rgba(4, 0, 255, 0.1);
    padding: 20px;
    border-radius: 15px;
    box-shadow: 0 8px 12px
        rgba(0, 255, 128, 0.2);
    backdrop-filter: blur(5px);
    text-align: center;
    animation: fadeIn 0.5s ease-in-out;
}
@keyframes fadeIn {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}
.title {
    font-size: 36px;
    color: green;
}
.subtitle {
    margin: 0;
    font-size: 18px;
    color: rgb(0, 0, 0);
}
.select-category,
.unit-select,
.input {
    padding: 12px;
    font-size: 16px;
    border: none;
    background: rgba(
        255,
        255,
        255,
        0.4
    );
    color: rgb(0, 0, 0);
    border-radius: 10px;
}
.arrow {
    font-size: 20px;
    color: #3494e6;
}
.convert-button {
    padding: 12px 24px;
    font-size: 16px;
    background: #f9a826;
    color: #fff;
    border: none;
    border-radius: 10px;
    cursor: pointer;
    transition: background 0.3s;
}
.convert-button:hover {
    background: #ecd56e;
}
.result {
    background: rgba(
        255,
        255,
        255,
        0.3
    );
    padding: 10px;
    margin: 10px;
    border-radius: 10px;
    animation: fadeIn 0.5s ease-in-out;
}
.result p {
    font-size: 18px;
    color: rgb(0, 0, 0);
}
.conversion {
    background: rgba(255, 0, 0, 0.3);
    padding: 20px;
    margin: 10px;
    border-radius: 15px;
    backdrop-filter: blur(5px);
    transition: transform 0.3s,
        box-shadow 0.3s;
    animation: fadeIn 0.5s ease-in-out;
}
.conversion:hover {
    transform: scale(1.03);
    box-shadow: 0 10px 16px
        rgba(0, 0, 0, 0.25);
}


Output:

Unit



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads