A temperature converter is a simple but practical project if you're learning JavaScript and want to apply your skills to something real. It teaches you how to:
- Work with HTML input fields
- Use JavaScript functions
- Perform mathematical operations
- Dynamically update the DOM
In this guide, we’ll create a small app that converts temperatures between Celsius and Fahrenheit using plain HTML and JavaScript.
How It Works
The app includes:
- A number input where the user enters a temperature.
- A dropdown menu to choose the type of conversion (Celsius to Fahrenheit or vice versa).
- A button to perform the conversion.
- A paragraph to show the result.
When the user clicks the button, JavaScript takes the input, applies the correct formula, and shows the result.
** The HTML Structure**
The HTML contains the layout: input field, dropdown, button, and result display.
<input type="number" id="temperatureInput" placeholder="Enter temperature" />
<select id="unitSelect">
<option value="c-to-f">Celsius to Fahrenheit</option>
<option value="f-to-c">Fahrenheit to Celsius</option>
</select>
<button onclick="convertTemperature()">Convert</button>
<p id="result"></p>
function convertTemperature() {
const tempInput = document.getElementById("temperatureInput").value;
const conversionType = document.getElementById("unitSelect").value;
const resultElement = document.getElementById("result");
if (tempInput === "") {
resultElement.textContent = "Please enter a valid temperature.";
return;
}
const temp = parseFloat(tempInput);
let result;
if (conversionType === "c-to-f") {
result = (temp * 9/5) + 32;
resultElement.textContent = ${temp}°C = ${result.toFixed(2)}°F
;
} else if (conversionType === "f-to-c") {
result = (temp - 32) * 5/9;
resultElement.textContent = ${temp}°F = ${result.toFixed(2)}°C
;
} else {
resultElement.textContent = "Unknown conversion type.";
}
}
**What the Code Does:**
1. Grabs the user input and conversion choice.
2. Checks if input is valid.
3. Applies the correct formula:
4. °F = (°C × 9/5) + 32
5. °C = (°F − 32) × 5/9
6. Displays the result on the page.
**What You Can Add Next**
Want to expand it? Try these ideas:
- Add input validation for letters or symbols.
- Style the app using CSS.
- Add Kelvin as a third temperature unit.
- Store conversions in local storage.
Top comments (1)
I initially visited to try it out, but ended up staying. River Cree Casino CA captivated me from the first game. The first deposit bonus was a pleasant surprise. I especially enjoyed the selection of slots, ranging from classic to modern themes. Everything functions smoothly. I recommend it for enjoyable and fair entertainment.