How to build a Weather Converter with HTML, CSS and Vanilla JavaScript (Part 2-Adding JavaScript)
Tags: javascript, webdev, beginners, tutorial
Published: 2021-11-13 21:54:29

In [part 1](https://dev.to/codergirl1991/how-to-build-a-weather-converter-with-html-css-and-vanilla-javascript-part-1-basic-setup-1h3g), we built out the HTML file for the weather converter project.

In [part 2](https://dev.to/codergirl1991/how-to-build-a-weather-converter-with-html-css-and-vanilla-javascript-part-2-adding-javascript-59f1), we will build out the JavaScript functionality.

## What you will learn in Part 2
* How to use `document.getElementById`
* How to use Template literals
* How to use `addEventListener`

## How to use `document.getElementById`
The `document.getElementById` method, allows us to access elements in the HTML file with that `id` name. 

The first element we want to access is the `input` element.

Inside the `index.js` file, use the `document.getElementById` method to access the number input and assign it to the variable called `numInputValue`.

```js
const numInputValue = document.getElementById("number");
```

Next, access the convert button and assign it to the `convertBtn` variable.
```js
const convertBtn = document.getElementById("convert");
```
Then access the `result-div` and assign it to the `result` variable.
```js
const result = document.getElementById("result");
```
Lastly, access the reset button and assign it to the `resetBtn` variable.
```js
const resetBtn = document.getElementById("reset");
```
This is what our code looks like so far in the `index.js` file.

```js
const numInputValue = document.getElementById("number");
const convertBtn = document.getElementById("convert");
const result = document.getElementById("result");
const resetBtn = document.getElementById("reset");
```
## Creating the temperature converter function
Every time the user clicks on the `convert` button, this function will fire and show the results to the user.

First, create an arrow function called `temperatureConverter`.
```js
const temperatureConverter = () => {

}
```
Inside the function, we need to get the user input from the value attribute and save it to a variable.
 
We can achieve this by using the value property in JavaScript. 
```js
let userInput = numInputValue.value;
```
The next thing we need to do is calculate the celsius to fahrenheit conversion.

This is the algorithm we will be using.
```js
(Celsius * 9/5) + 32
```
The `userInput` represents celsius and we want to round the calculation down to the nearest whole integer using `Math.floor`.

We will assign this result to a variable called `fahrenheit`. 
```js
let fahrenheit = Math.floor((userInput * 9) / 5 + 32);
```
We will then create a template string which shows the conversion results to the user.
```js
const conversionString = `<p>${userInput} degrees Celsius is</p> <p>${fahrenheit} degrees Fahrenheit </p>`;
```
Then we will create an array of responses based on if the weather temperature is nice, hot, or cold. We will also have a response for invalid user inputs.

```js
const responsesArr = [
    "Invalid input. Try again.",
    `<p class="result-text">Ohh..that's HOT<i class="fas fa-burn"></i></p>${conversionString}`,
    `<p class="result-text">Not to bad<i class="far fa-sun"></i></p> ${conversionString}`,
    `<p class="result-text">Getting colder <i class="fas fa-icicles"></i></p>${conversionString}`
  ];
```
The last component of the converter function, is to create an `if/else` statement which will determine the correct response to be shown to the user based on the input results. 

The first condition will check if the user does not provide an input or if the user provides an input that falls outside of the given number range of -90 through 57.

If it is an invalid input, then we will use the `innerHTML` method to show the user the invalid response from the `responsesArr`. 

```js
   if (userInput > 57 || userInput < -90 || userInput === "") {
        result.innerHTML = responsesArr[0];
    }
```

If the input is between 30 and 57, then we will show the "Ohh..that's HOT" message to the user. 
```js
else if (userInput >= 30 && userInput <= 57) {
        result.innerHTML = responsesArr[1];
    }
```
If the input is between 20 and 29, then we will show the "Not to bad" message to the user. 
```js
else if (userInput >= 20 && userInput <= 29) {
    result.innerHTML = responsesArr[2];
  }
```
If the input is 19 or below, then we will show the "Getting colder" message to the user.
```js
 else {
    result.innerHTML = responsesArr[3];
  }
```
This is what the entire `temperatureConverter` function should look like.

```js
const temperatureConverter = () => {
    let userInput = numInputValue.value;
    let fahrenheit = Math.floor((userInput * 9) / 5 + 32);
    const conversionString = `<p>${userInput} degrees Celsius is</p> <p>${fahrenheit} degrees Fahrenheit </p>`;
    const responsesArr = [
        "Invalid input. Try again.",
        `<p class="result-text">Ohh..that's HOT<i class="fas fa-burn"></i></p>${conversionString}`,
        `<p class="result-text">Not to bad<i class="far fa-sun"></i></p> ${conversionString}`,
        `<p class="result-text">Getting colder <i class="fas fa-icicles"></i></p>${conversionString}`
    ];

    if (userInput > 57 || userInput < -90 || userInput === "") {
        result.innerHTML = responsesArr[0];
    } else if (userInput >= 30 && userInput <= 57) {
        result.innerHTML = responsesArr[1];
    } else if (userInput >= 20 && userInput <= 29) {
        result.innerHTML = responsesArr[2];
    } else {
        result.innerHTML = responsesArr[3];
    }
};
```
## How to use the `addEventListener` method
The `addEventListener` method in JavaScript will listen for a specific event and then will execute a function for that event.

The event we are listening for is a `click` event. When the user clicks on the convert button, then our `temperatureConverter` function will execute. 

Add this event listener, just below the `temperatureConverter` function.
```js
convertBtn.addEventListener("click", temperatureConverter);
```
Start the local server in VS Code by clicking on the `Go Live` button in the bottom right hand corner.
![go live button](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xnkwn4kqgxjyi6ecz5r2.png)
 
Then click on the `convert` button and you should see the invalid message show up.
![invalid message](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/91tbqo1uyfvg949cupdr.png)
 
Now try to enter in the number 45 and you should see the proper conversion and message.

![testing inputs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kt8pc33pziqzdewbhr0o.png)
  
Right now, the `temperatureConverter` function only runs if the user clicks on the `convert` button. But we also want to add the functionality for the user to hit the `enter` key and have the results still show up.

We can add another event listener to listen for `keydown` events and execute the `temperatureConverter` if the `enter` key is pressed.

```js
numInputValue.addEventListener("keydown", (e) => {
  if (e.key === "Enter") {
    temperatureConverter(e);
  }
});
```
The `e` parameter represents the event object being executed.

If the user does not provide an input and hits the enter key then we can show an invalid message.

```js
document.body.addEventListener("keydown", (e) => {
  if (e.key === "Enter" && numInputValue.value === "") {
    result.innerHTML = "Please provide an input.";
  }
});
```
The last part of our JavaScript code, is to create the reset function.

We can use another event listener to clear out the results when the user clicks on the `reset` button.

```js
resetBtn.addEventListener("click", () => {
  result.innerHTML = '<i class="fas fa-fire"></i>';
  numInputValue.value = "";
});
```
Try entering in a valid input and then clicking on the reset button. You should see that the results were successfully cleared out. 

This is the entire code for the JavaScript file.
```js
const numInputValue = document.getElementById("number");
const convertBtn = document.getElementById("convert");
const result = document.getElementById("result");
const resetBtn = document.getElementById("reset");

const temperatureConverter = () => {
    let userInput = numInputValue.value;
    let fahrenheit = Math.floor((userInput * 9) / 5 + 32);
    const conversionString = `<p>${userInput} degrees Celsius is</p> <p>${fahrenheit} degrees Fahrenheit </p>`;
    const responsesArr = [
        "Invalid input. Try again.",
        `<p class="result-text">Ohh..that's HOT<i class="fas fa-burn"></i></p>${conversionString}`,
        `<p class="result-text">Not to bad<i class="far fa-sun"></i></p> ${conversionString}`,
        `<p class="result-text">Getting colder <i class="fas fa-icicles"></i></p>${conversionString}`
    ];

    if (userInput > 57 || userInput < -90 || userInput === "") {
        result.innerHTML = responsesArr[0];
    } else if (userInput >= 30 && userInput <= 57) {
        result.innerHTML = responsesArr[1];
    } else if (userInput >= 20 && userInput <= 29) {
        result.innerHTML = responsesArr[2];
    } else {
        result.innerHTML = responsesArr[3];
    }
};

convertBtn.addEventListener("click", temperatureConverter);

numInputValue.addEventListener("keydown", (e) => {
    if (e.key === "Enter") {
        temperatureConverter(e);
    }
});

document.body.addEventListener("keydown", (e) => {
    if (e.key === "Enter" && numInputValue.value === "") {
        result.innerHTML = "Please provide an input.";
    }
});

resetBtn.addEventListener("click", () => {
    result.innerHTML = '<i class="fas fa-fire"></i>';
    numInputValue.value = "";
});
```
In part 3, we will add all of the CSS styles to the project.

[Final code](https://github.com/jdwilkin4/Weather-Converter-Project)