Simple Temperature Converter in JavaScript

Simple Temperature Converter in JavaScript
Code Snippet:Simple Temperature Converter in Vanilla HTML, CSS, and JavaScript
Author: CodeMentorUK
Published: January 19, 2024
Last Updated: January 22, 2024
Downloads: 1,088
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code snippet helps you to create a temperature converter. It allows users to easily convert temperatures between Celsius and Fahrenheit. It functions by taking your temperature input and unit choice, and then instantly providing the converted temperature. This tool is helpful for quick temperature conversions.

If you’re developing a weather app, you can integrate this temperature converter to offer users the convenience of switching between Celsius and Fahrenheit for weather forecasts. Moreover, you can customize the interface of the converter with additional CSS according to your needs.

How to Create a Simple Temperature Converter in JavaScript

1. First, create the HTML code as follows to set up the basic structure of our temperature converter. It includes input fields for temperature and unit selection, a conversion button, and a result display area.

 <div class="container">
        <h1>Temperature Converter</h1>
        <div class="form-group">
            <label for="temperature">Enter Temperature:</label>
            <input type="text" id="temperature" placeholder="Enter temperature">
        </div>
        <div class="form-group">
            <label for="unit">Choose Unit:</label>
            <select id="unit">
                <option value="C">Celsius</option>
                <option value="F">Fahrenheit</option>
            </select>
        </div>
        <button id="convertBtn">Convert</button>
        <div id="result"></div>
    </div>

2. Create a CSS file (styles.css) and add the following styles to make the converter visually appealing:

body {
    font-family: Arial, sans-serif;
}

.container {
    max-width: 400px;
    margin: auto;
    padding: 20px;
    border-radius: 5px;
    background: rgba(255, 255, 255, 0.89);
   color: #333;
}

.form-group {
    margin-bottom: 20px;
}
.form-group h1{
  color: #007bff;
}
label {
    display: block;
    margin-bottom: 10px;
}

input, select {
    width: 100%;
    padding: 10px;
    border: none;
    border-radius: 5px;
   box-sizing: border-box
}

button {
    padding: 10px 20px;
    background-color: #007bff;
    color: #ffffff;
    border: none;
    border-radius: 5px;
}

#result {
    margin-top: 20px;
}

3. Now, let’s create the JavaScript file (script.js) to add the functionality to our temperature converter. It defines the logic for converting temperatures between Celsius and Fahrenheit and displays the result on the web page.

// Get references to HTML elements
const temperatureInput = document.getElementById('temperature');
const unitSelect = document.getElementById('unit');
const convertBtn = document.getElementById('convertBtn');
const resultDiv = document.getElementById('result');

// Function to convert temperature
function convertTemperature() {
    const temp = parseFloat(temperatureInput.value);
    const unit = unitSelect.value;

    // Error handling
    if (isNaN(temp)) {
        resultDiv.innerHTML = 'Please enter a valid number.';
        return;
    }

    let convertedTemp;
    if (unit === 'C') {
        // Convert Celsius to Fahrenheit
        convertedTemp = (temp * 9/5) + 32;
    } else {
        // Convert Fahrenheit to Celsius
        convertedTemp = (temp - 32) * 5/9;
    }

    resultDiv.innerHTML = `Converted Temperature: ${convertedTemp.toFixed(2)}°${unit === 'C' ? 'F' : 'C'}`;
}

// Add event listener for the Convert button
convertBtn.addEventListener('click', convertTemperature);

That’s all! Hopefully, you’ve successfully integrated this simple temperature converter into your web/app project. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X