JavaScript - 30
JavaScript - 30: Mini Project - Weather Card (Mock)
Create a mock weather card that shows stored weather data for a few example cities.
Your challenge: Read the city name, look it up in an object, and display the matching weather data in both Celsius and Fahrenheit.
Look up the city
The weather information is stored inside the weatherData object.
After reading the input, use weatherData[city] to look for a matching city.
Convert Celsius to Fahrenheit
The stored temperature is in Celsius. You can convert it to Fahrenheit with:
(data.temp * 9 / 5) + 32
Use Math.round() if you want a whole-number temperature.
Display both temperatures
You can show both values together, such as: 18°C / 64°F.
Handle missing cities
If the object does not contain that city, display a simple message instead.
Try it: Search for each city in the mock data and compare the Celsius and Fahrenheit values.
Good JavaScript habit: Keep one main temperature value in your data and calculate the other when you need it instead of storing the same information twice.
👀 Show Solution
const cityInput = document.getElementById("cityInput");
const getWeatherBtn = document.getElementById("getWeather");
const weatherCard = document.getElementById("weatherCard");
const weatherData = {
"pine harbor": {
temp: 18,
condition: "Cloudy",
humidity: 72
},
"maple bay": {
temp: 24,
condition: "Sunny",
humidity: 45
},
"cedar point": {
temp: 22,
condition: "Rainy",
humidity: 85
},
"silver lake": {
temp: 17,
condition: "Partly Cloudy",
humidity: 60
}
};
getWeatherBtn.addEventListener("click", function() {
const city = cityInput.value.trim().toLowerCase();
const cityName = document.getElementById("cityName");
const temperature = document.getElementById("temperature");
const condition = document.getElementById("condition");
const humidity = document.getElementById("humidity");
const weatherMessage = document.getElementById("weatherMessage");
weatherCard.style.display = "block";
if (weatherData[city]) {
const data = weatherData[city];
const fahrenheit = Math.round(
(data.temp * 9 / 5) + 32
);
cityName.textContent = cityInput.value.trim();
temperature.textContent =
data.temp + "°C / " + fahrenheit + "°F";
condition.textContent = data.condition;
humidity.textContent =
"Humidity: " + data.humidity + "%";
weatherMessage.textContent = "";
} else {
cityName.textContent = "";
temperature.textContent = "";
condition.textContent = "";
humidity.textContent = "";
weatherMessage.textContent =
"City not found in the mock weather data.";
}
});The weather data stores the Celsius temperature once. JavaScript converts that value to Fahrenheit before displaying both temperatures in the weather card.
