This content originally appeared on DEV Community and was authored by Jessica Wilkins
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");
Next, access the convert button and assign it to the convertBtn
variable.
const convertBtn = document.getElementById("convert");
Then access the result-div
and assign it to the result
variable.
const result = document.getElementById("result");
Lastly, access the reset button and assign it to the resetBtn
variable.
const resetBtn = document.getElementById("reset");
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");
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 = () => {
}
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;
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
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);
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>`;
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}`
];
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];
}
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];
}
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];
}
If the input is 19 or below, then we will show the "Getting colder" message to the user.
else {
result.innerHTML = responsesArr[3];
}
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];
}
};
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);
Start the local server in VS Code by clicking on the Go Live
button in the bottom right hand corner.
Then click on the convert
button and you should see the invalid message show up.
Now try to enter in the number 45 and you should see the proper conversion and message.
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);
}
});
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.";
}
});
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 = "";
});
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 = "";
});
In part 3, we will add all of the CSS styles to the project.
This content originally appeared on DEV Community and was authored by Jessica Wilkins
Jessica Wilkins | Sciencx (2021-11-13T21:54:29+00:00) How to build a Weather Converter with HTML, CSS and Vanilla JavaScript (Part 2-Adding JavaScript). Retrieved from https://www.scien.cx/2021/11/13/how-to-build-a-weather-converter-with-html-css-and-vanilla-javascript-part-2-adding-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.