A Step-by-step Tutorial for Building a Temperature Converter Website
Tags: tutorial, programming, javascript, beginners
Published: 2021-09-22 08:50:02

Building coding projects is one of the best ways to learn coding and build your portfolio. However, sometimes a simple project spec may not be enough to help you build your project. This tutorial will walk you through how to build a [Temperature converter website](https://www.codementor.io/projects/web/temperature-converter-website-atx32dy7mf?utm_source=devto&utm_medium=blog&utm_campaign=tempconvert), one of the most popular projects on [DevProjects](https://www.codementor.io/projects?utm_source=devto&utm_medium=blog&utm_campaign=tempconvert).

You’ll build a simple tool to convert between different temperature units. To follow along, check out the [project spec on DevProjects](https://www.codementor.io/projects?utm_source=devto&utm_medium=blog&utm_campaign=tempconvert)!🚀

## Introduction
While Kelvin is the SI Unit of temperature, people generally prefer Fahrenheit or Celsius unit type to measure temperature. We're going to build a temperature converter that will convert Fahrenheit, Celsius, and Kelvin units to each other, using the most popular CSS framework called [Bootstrap 4.6](https://getbootstrap.com/docs/4.6/getting-started/introduction/) and JavaScript library - [jQuery](https://jquery.com/). 

Here is the live demo of [Temperature converter website](https://karan-kmr.github.io/temperature-converter/).

## Project Overview
In this tutorial, we will create a temperature converter and walk through how the website works. We will deploy this project on GitHub using GitHub pages, a hosting service by GitHub that allows you to publish static websites online directly from repositories. The tutorial will guide you through the step-by-step process of setting up the GitHub repositories before publishing the website. The suggested text editor is VScode, but you can choose any other text editor you like.

⭐ **Why** **Bootstrap**

We are using this library because of its variety of components. Additionally, the bootstrap grid system is based on Flex, which provides us with full responsive support for any website. You can read more about it on its official website.

⭐ **Why** **jQuery**

While other powerful libraries and frameworks have emerged, jQuery is very beginner friendly and is the best library for practicing and getting started in JavaScript libraries.

jQuery is a small, fast, and feature-rich library. It saves developers a lot of time by completing complicated tasks with just a few lines of code.

⭐ **What you need**

- VSCode or any other text editor
- Any browser of your choice
- Basics knowledge of jQuery and Bootstrap
- A GitHub Account for deployment

[Recreate this project on DevProjects. Try it now!](https://www.codementor.io/projects/web/temperature-converter-website-atx32dy7mf?utm_source=devto&utm_medium=blog&utm_campaign=tempconvert)

## Setting up the project environment

1. Create a new folder named Temperature Converter and open the folder in VScode. Initially, our workspace will look like this:
![image1.png](https://ucarecdn.com/1a975794-634b-4e84-b03a-e42e7897d594/)

	Hover the mouse on the sidebar to find the icon for creating new files or folders
    ![image2.png](https://ucarecdn.com/c36c9f8d-07bf-4cf5-9cea-9c442b81f59b/)

2. Create a sub-folder named assets and the following files: index.html, style.css, and script.js.

	![fileDirectory.png](https://ucarecdn.com/54828960-0022-4f60-8f67-0b54f2ac01e9/)

**Assets**
In this folder, we'll store all icons and any other media used in our project.

**Index.html**
To create the structure of the website.

**Style.css**
To add custom CSS styling in our project.

**Script.js**
This is like the brain of our project, In which we write JavaScript code to make our website work.

3. Open the index.html type doc then press enter, A boilerplate will appear as shown below:
    ![image3.png](https://ucarecdn.com/8c866a09-7ceb-4816-82aa-d1d338b9ab99/)

4. Open the index.html type doc then press enter, A boilerplate will appear as shown below:
       
      a. Set up Bootstrap 4.6 CSS
       ![image4.png](https://ucarecdn.com/1b50054e-8df3-4cb1-b5fd-8214a7c577fa/)

Visit Official Bootstrap 4.6.0 Documentation and copy the CDN link of the CSS and JS Bundle. Alternatively, you can also use this Boilerplate in your index.html

```
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Tempreature Unit Converter</title>
      <!-- ---------------Bootstrap 4.6-------------------------------------- -->
      <link rel="stylesheet"
         href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css"
         integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l"
         crossorigin="anonymous">
      <!-- ---------------Custom CSS-------------------------------------- -->
      <link rel="stylesheet" href="style.css">
   </head>
   <body class="d-flex align-items-center">



      <!-- All body content will come here -->




      <!-- ---------------jQery-------------------------------------- -->
      <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
         integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
         crossorigin="anonymous"></script>
      <script
         src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"
         integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns"
         crossorigin="anonymous"></script>
      <!-- ---------------Custom JS-------------------------------------- -->
      <script src="script.js"></script>
   </body>
</html>
```
[Why not build this project yourself? Build this project for free.](https://www.codementor.io/projects/web/temperature-converter-website-atx32dy7mf?utm_source=devto&utm_medium=tempconvertblog)

## Let's Start Building
The project will be divided into 5 steps:
![steps.png](https://ucarecdn.com/275da153-8dcc-4767-ade3-b88f100caa20/)

### Step 0 : Create HTML structure with Bootstrap classes
![image5.png](https://ucarecdn.com/a7ca8c5b-c4d6-4028-a317-89f9a956673e/)
1. Create the container, then make our card-group. The card-group will contain both input-card and result-card. The structure code will look something like this:
```
<div class="container">
  <div class="row">
    <div class="card-group col-12 col-md-10 offset-md-1 my-md-auto">
      <!-- Input and Result Section will come here-->
    </div>
  </div>
</div>
```
2. Add the input & result card section with custom CSS class `inputSection` to enter input values, and `resultSection` to display the result value.
```html
<div class="card inputSection col-12 col-md-6">
  <div class="card-body">
    <form>
      <div class="row px-3">
        <div class="col-12 col-md-11 px-4">
          <span class="card-title d-block">Enter Temperature</span>
          <label for="degreeInput" class="py-sm-2">Degree</label>
          <div class="input-group">
            <input type="number" class="form-control" id="inputDegree" name="inputDegree" placeholder="Enter Degree" value="0" />
            <div class="input-group-append">
              <select class="form-control" id="selectInputDegreeType">
                <option value="C" selected>&deg;C</option>
                <option value="F">&deg;F</option>
                <option value="K">K</option>
              </select>
            </div>
          </div>
          <label for="selectConversionType" class="py-sm-2">Convert In</label>
          <div class="input-group d-inline-block">
            <div class="input-group-append">
              <select class="form-control" id="selectConversionType">
                <option value="F" selected> Fahrenheit (&deg;F) </option>
                <option value="C">Celcius (&deg;C)</option>
                <option value="K">Kelvin (K)</option>
              </select>
            </div>
          </div>
          <button type="submit" class="convertBtn
                                btn btn-lg
                                col-12 col-md-6
                                offset-md-3
                                mt-4
                                rounded-pill
                                d-flex
                                justify-content-center
                                align-items-center
                                text-white"> Convert&emsp; <svg class="mt-1" xmlns="http://www.w3.org/2000/svg" width="15px" height="15px" viewBox="0 0 21.367 20.826">
              <path id="Icon_awesome-arrow-right" data-name="Icon awesome-arrow-right" d="M9.085,4.042l1.059-1.059a1.14,1.14,0,0,1,1.617,0l9.271,9.266a1.14,1.14,0,0,1,0,1.617L11.76,23.137a1.14,1.14,0,0,1-1.617,0L9.085,22.078A1.146,1.146,0,0,1,9.1,20.443l5.747-5.475H1.145A1.142,1.142,0,0,1,0,13.823V12.3a1.142,1.142,0,0,1,1.145-1.145H14.85L9.1,5.678A1.138,1.138,0,0,1,9.085,4.042Z" transform="translate(0 -2.647)" fill="#fff" />
            </svg>
          </button>
        </div>
      </div>
    </form>
  </div>
</div>
<div class="card resultSection col-12 col-md-6">
  <div class="card-body d-flex justify-content-center
                align-items-center">
    <div id="resultValueSection">
      <div id="convertedDegree">32</div>
      <h3 id="degree">&deg;</h3>
      <h3 id="convertedUnit">F</h3>
    </div>
  </div>
</div>
```   
By finishing the two steps above, we’ve completed the structure part.. Your output will look something like this:
![demo1.jpeg](https://ucarecdn.com/ff80e28b-3d97-4aae-879f-7a757a6d346f/)

Doesn’t look like our final design? Don’t worry. In the next step, we use custom CSS to style and design our website.

**Useful references**

- [Bootstrap Layout](https://getbootstrap.com/docs/4.6/layout/overview/)
- [Bootstrap Cards](https://getbootstrap.com/docs/4.6/components/card/)
- [Bootstrap Input-Groups](https://getbootstrap.com/docs/4.6/components/input-group/)
- [Bootstrap Forms](https://getbootstrap.com/docs/4.6/components/forms/)

### Step 1: Add custom CSS styling
1. Use the [reference code](https://www.notion.so/472681e481af54f417febc5fc8bbee65) to add styling or add your own custom styles.

Your result will look something like this: 

**On small screens or mobile:**
![image6.png](https://ucarecdn.com/d84004e0-0e56-4b1b-86d6-47bd124f3358/)

**On medium to large screen or PC:**
![image7.jpeg](https://ucarecdn.com/f7f9db4f-1970-421e-a8b4-4adb5c99dda8/)

Now that we've completed all our styling work at this stage, simply add JS functionality and then the project is ready to deploy.

[You can build this project yourself! Start the project now.](https://www.codementor.io/projects/web/temperature-converter-website-atx32dy7mf?utm_source=devto&utm_medium=blog&utm_campaign=tempconvert)

### Step 2: Create convert functions for all three units
It's time to create the functions that will convert our input degree to the desired unit. First, let's understand how this works.
![Diagram.png](https://ucarecdn.com/e9796b80-270f-47b0-9780-e4c27d7f3ca2/)

Our function will take two arguments: `input temperature value` and `output temperature unit type`. The function will check the output unit type, apply the formula according to the `output temperature unit type`, and return the converted value.

1. **Fahrenheit Converter ( °F  ⇒** °C or K **)**

	This function will only convert the Fahrenheit temperature value into Celsius or Kelvin. So whenever the user enters a °F value, we have to call this function. The reference code is shown below:


    ```jsx
    // Fahrenheit Converter
    function fTo(inputDegreeValue, conversionDegreeType) {

    	let temperature = '';

    	switch (conversionDegreeType) {
    		case 'F':
    			temperature = inputDegreeValue;
    			break;
    		case 'C':
    			temperature = eval((inputDegreeValue - 32) * (5 / 9));
    			break;
    		case 'K':

    			temperature = eval((inputDegreeValue + 459.67) * (5 / 9));
    			break;

    	}
    	return temperature;
    }
    ```


2. **Celsius** **Converter ( °C  ⇒** °F or K **)**

    This function will only convert the Celsius temperature value into Fahrenheit or Kelvin. So whenever the user enters a °C value, we have to call this function. The reference code is shown below:

    ```jsx
    // Celcius Converter

    function cTo(inputDegreeValue, conversionDegreeType) {

    	let temperature = '';

    	switch (conversionDegreeType) {

    		case 'C':
    			temperature = inputDegreeValue;
    			break;
    		case 'F':
    			temperature = eval((inputDegreeValue * (9 / 5)) + 32);
    			break;
    		case 'K':
    			temperature = eval(inputDegreeValue + 273.15);
    			break;

    	}

    	return temperature;
    }
    ```
3. **Kelvin** **Converter ( K  ⇒** °F or °C **)**

	This function will only convert Kelvin temperature value into Fahrenheit or Celsius. When a user enters a K value, we have to call this function. The reference code is shown below:

	```
    // Kelvin Converter

	function kTo(inputDegreeValue, conversionDegreeType) {

	let temperature = '';

	switch (conversionDegreeType) {
		case 'K':
			temperature = inputDegreeValue;
			break;
		case 'F':
			temperature = eval((inputDegreeValue - 273.15) * (9 / 5) + 32);
			break;
		case 'C':
			temperature = eval((inputDegreeValue - 273.15));
			break;

	}
	return temperature;
	}
	```

[Got stuck on the project? Find a Javascript expert here!](https://www.codementor.io/search/mentors?q=javascript?utm_source=devto&utm_medium=blog&utm_campaign=tempconvert)

### Step 3: Receive user input and send output on webpage
This is where DOM comes in. Whenever user click submit button, the output should appear in the results section. We'll do this by creating a function, `convertInputDegree()`. This function will take the user inputs, check the type of input degree unit, and call the function we created in step 2.

If the user has entered a Celsius degree unit and wants to convert it into Kelvin, the function will take the `input degree value` and `input degree unit` and call the `cTo()` function. Then the `cTo()` function will check the `output unit type` and returns the appropriate result. The result will be stored in a variable `resultValue` and the value will be pushed into the result section.

1. As we want the `input value` when user submit the form but default behavior of form after submit button is clicked to take the input values from user level to server level and page will be redirect to the current URL by appending the input values as query string parameters and value of the input field will revert back to **0**. 

    That's why on form submission we are calling `convertInputDegree()`  instead of it's default action.

    ```jsx
    // On Form submission prevent the default action and call the function to update the result

    $('form').submit(function (event) {
        event.preventDefault(); // to prevent the default action
        convertInputDegree()
    });
    ```

1. Create `convertInputDegree()` function to update results.

    ```jsx
    function convertInputDegree() {

    	let inputDegree = parseInt($('#inputDegree').val());
    	let selectInputDegreeType = $('#selectInputDegreeType').val();
    	let conversionType = $('#selectConversionType').val();

    	let resultValue = "";

    	switch (selectInputDegreeType) {

    		case "C":
    			resultValue = cTo(inputDegree, conversionType);
    			break;

    		case "F":
    			resultValue = fTo(inputDegree, conversionType);
    			break;

    		case "K":
    			resultValue = kTo(inputDegree, conversionType);
    			break;

    	}

    	// To prevent NaN
    	if (isNaN(inputDegree)) {
    		$('#convertedDegree').text('');
    		return;
    	}

    	// To update the Degree Unit
    	$('#convertedUnit').text(conversionType)

    	// To update the Degree Value
    	if (conversionType === selectInputDegreeType) {

    		$('#convertedDegree').text(inputDegree);
    	} else {

    		return $('#convertedDegree').text(resultValue.toFixed(2));

    	}

    }
 	```

[Got questions? Find a Javascript expert to help you.](https://www.codementor.io/search/mentors?q=javascript?utm_source=devto&utm_medium=blog&utm_campaign=tempconvert)

### Step 4: **Update results in real-time**

We’re almost finished building our temperature converter! However, there’s one but if the users have to click the submit button again and again, it will provide a bad user experience. We can fix this by updating the output value in real-time. To do this, we can call the function `convertInputDegree()` when users select a different input or output unit. The code should look like this:

```jsx
// Realtime Update
$('#inputDegree').on('input', () => convertInputDegree());
$('#selectInputDegreeType').change(() => convertInputDegree());
$('#selectConversionType').change(() => convertInputDegree());
```

## Result

Once we've completed all of the above steps, this is what the final preview will look like:
![result.gif](https://ucarecdn.com/891c854f-e22b-4dd9-9d9f-98b66a9e217e/)

[Want to build this project? Start building now!](https://www.codementor.io/projects/web/temperature-converter-website-atx32dy7mf?utm_source=devto&utm_medium=blog&utm_campaign=tempconvert)

## Time to deploy
The last thing to do is to deploy the website using GitHub pages. In order to use GitHub pages, we have to make a GitHub repository for this project first.

### 1. **Create a GitHub repository**

1. Open your browser and go to [https://github.com/](https://github.com/) and make sure you're logged In. 
2. Click on the `+` icon on the navbar in the top right corner:
	![deploy1.png](https://ucarecdn.com/a9609733-47e2-4c60-9bea-06314902c7b9/)

3. Click on `New repository` in the drop-down box:
        ![deploy2.png](https://ucarecdn.com/65b7653d-4af0-4133-b528-4cfd7175b3e6/)

4. Enter the name of the repository, keep everything default, and click `Create repository` on the new page:

       ![deploy3.png](https://ucarecdn.com/e3cf09b3-d6d3-4fb4-9c4d-21eeca557bbd/)

5. Our repository has been created. Copy the highlighted line to VSCode:

       ![deploy4.png](https://ucarecdn.com/8567e0a0-0da0-4675-bab7-f741bc51d473/)

### 2. **Initialize Git in your project**

1. Open a new terminal in VSCode and type this command. This command will:

    ```bash
    git init
    git add .
    git branch -M master
    git commit -m "Your message"
    ```

1. Sync our online GitHub repository with local repository 

    ```bash
    git remote add origin https://github.com/karan-kmr/Temperature-unit-converter.git
    ```

2. Command to push or send your files to the online repository:

    ```bash
    git push -u origin master
    ```

3. Refresh the GitHub repository page:

    ![deploy5.png](https://ucarecdn.com/0bba6f62-0fa3-4e0e-b2f3-a683400c2e29/)

    All of our project files have been pushed to our GitHub repo. 

    There are only two more steps to making our website live! 💪🏼

### 3. **Setup GitHub Pages**

Here are the steps to setup GitHub pages for your project:

1. Go to `Settings`
2. Scroll down and click on `pages`
3. Change branch from `none` to `master`
4. Click on `Save` button
5. Our site is live 🎉

If the steps above aren't clear enough, here's a video to help you out:

@[Demo](https://youtu.be/bK5s0HhiORI)

Here is the [Project Demo](https://www.codementor.io/project-solutions/cq6kpyhvu9?ref=tempconvertblog) and [Source Code](https://github.com/karan-kmr/temperature-converter).

## Recap

Here are some of the things we created in this tutorial:

- A full structure using Bootstrap classes.
- A fully responsive website.
- A temperature converter that allows users to cover from Fahrenheit, Celsius, and Kelvin to each other.
- A website that updated the output in real time

**Congratulations! 🎉 You've successfully created a temperature converter website.**

[![alpaca.gif](https://ucarecdn.com/82725990-3199-485a-a2d1-3b85aed0479d/)](https://www.codementor.io/projects?utm_source=devto&utm_medium=blog&utm_campaign=tempconvert)