,

JavaScript Temperature Calculator: A Simple Project for Beginners with Source Code

Posted by








JavaScript Simple Projects for Beginners – Temperature Calculator

JavaScript Simple Projects for Beginners – Temperature Calculator

As a beginner in JavaScript, one of the best ways to learn the language is by building simple projects. One such project is a temperature calculator, which can convert temperatures from Celsius to Fahrenheit and vice versa. In this article, we will walk you through the process of building a temperature calculator using JavaScript.

HTML Structure

    
      <!DOCTYPE html>
      <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Temperature Calculator</title>
        <link rel="stylesheet" href="styles.css">
      </head>
      <body>
        <h1>Temperature Calculator</h1>
        <div class="input-group">
          <label for="celsius">Celsius:</label>
          <input type="number" id="celsius" placeholder="Enter temperature in Celsius">
        </div>
        <div class="input-group">
          <label for="fahrenheit">Fahrenheit:</label>
          <input type="number" id="fahrenheit" placeholder="Enter temperature in Fahrenheit">
        </div>
        <button onclick="convertToCelsius()">Convert to Celsius</button>
        <button onclick="convertToFahrenheit()">Convert to Fahrenheit</button>
        <script src="script.js"></script>
      </body>
      </html>
    
  

JavaScript Code (script.js)

    
      function convertToCelsius() {
        let fahrenheitInput = document.getElementById('fahrenheit').value;
        let celsiusOutput = (fahrenheitInput - 32) * (5/9);
        document.getElementById('celsius').value = celsiusOutput.toFixed(2);
      }

      function convertToFahrenheit() {
        let celsiusInput = document.getElementById('celsius').value;
        let fahrenheitOutput = (celsiusInput * (9/5)) + 32;
        document.getElementById('fahrenheit').value = fahrenheitOutput.toFixed(2);
      }
    
  

With this HTML and JavaScript code, you can create a simple temperature calculator that allows users to input a temperature in either Celsius or Fahrenheit and convert it to the other unit. This project is a great way for beginners to practice using JavaScript to manipulate user input and perform calculations based on that input.

Feel free to customize the project by adding additional features, such as input validation or styling with CSS. This simple project can serve as the foundation for more complex applications as you continue to improve your JavaScript skills.

For a complete source code of the project, you can access it on GitHub here.


0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Иван Наумик
7 months ago

Error when converting from Kelvin to Fahrenheit and from Kelvin to Rankine incorrect value.