DEV Community

Cover image for How to build a Weather Converter with HTML, CSS and Vanilla JavaScript (Part 2-Adding JavaScript)
Jessica Wilkins
Jessica Wilkins

Posted on • Edited on

How to build a Weather Converter with HTML, CSS and Vanilla JavaScript (Part 2-Adding JavaScript)

In part 1, we built out the HTML file for the weather converter project.

In part 2, 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.

const numInputValue = document.getElementById("number");
Enter fullscreen mode Exit fullscreen mode

Next, access the convert button and assign it to the convertBtn variable.

const convertBtn = document.getElementById("convert");
Enter fullscreen mode Exit fullscreen mode

Then access the result-div and assign it to the result variable.

const result = document.getElementById("result");
Enter fullscreen mode Exit fullscreen mode

Lastly, access the reset button and assign it to the resetBtn variable.

const resetBtn = document.getElementById("reset");
Enter fullscreen mode Exit fullscreen mode

This is what our code looks like so far in the index.js file.

const numInputValue = document.getElementById("number");
const convertBtn = document.getElementById("convert");
const result = document.getElementById("result");
const resetBtn = document.getElementById("reset");
Enter fullscreen mode Exit fullscreen mode

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.

const temperatureConverter = () => {

}
Enter fullscreen mode Exit fullscreen mode

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.

let userInput = numInputValue.value;
Enter fullscreen mode Exit fullscreen mode

The next thing we need to do is calculate the celsius to fahrenheit conversion.

This is the algorithm we will be using.

(Celsius * 9/5) + 32
Enter fullscreen mode Exit fullscreen mode

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.

let fahrenheit = Math.floor((userInput * 9) / 5 + 32);
Enter fullscreen mode Exit fullscreen mode

We will then create a template string which shows the conversion results to the user.

const conversionString = `<p>${userInput} degrees Celsius is</p> <p>${fahrenheit} degrees Fahrenheit </p>`;
Enter fullscreen mode Exit fullscreen mode

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.

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}`
  ];
Enter fullscreen mode Exit fullscreen mode

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.

   if (userInput > 57 || userInput < -90 || userInput === "") {
        result.innerHTML = responsesArr[0];
    }
Enter fullscreen mode Exit fullscreen mode

If the input is between 30 and 57, then we will show the "Ohh..that's HOT" message to the user.

else if (userInput >= 30 && userInput <= 57) {
        result.innerHTML = responsesArr[1];
    }
Enter fullscreen mode Exit fullscreen mode

If the input is between 20 and 29, then we will show the "Not to bad" message to the user.

else if (userInput >= 20 && userInput <= 29) {
    result.innerHTML = responsesArr[2];
  }
Enter fullscreen mode Exit fullscreen mode

If the input is 19 or below, then we will show the "Getting colder" message to the user.

 else {
    result.innerHTML = responsesArr[3];
  }
Enter fullscreen mode Exit fullscreen mode

This is what the entire temperatureConverter function should look like.

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];
    }
};
Enter fullscreen mode Exit fullscreen mode

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.

convertBtn.addEventListener("click", temperatureConverter);
Enter fullscreen mode Exit fullscreen mode

Start the local server in VS Code by clicking on the Go Live button in the bottom right hand corner.
go live button

Then click on the convert button and you should see the invalid message show up.
invalid message

Now try to enter in the number 45 and you should see the proper conversion and message.

testing inputs

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.

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

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.

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

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.

resetBtn.addEventListener("click", () => {
  result.innerHTML = '<i class="fas fa-fire"></i>';
  numInputValue.value = "";
});
Enter fullscreen mode Exit fullscreen mode

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.

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 = "";
});
Enter fullscreen mode Exit fullscreen mode

In part 3, we will add all of the CSS styles to the project.

Final code

Top comments (0)