The Code for Weather Now
const cityForm = document.querySelector("form");
const card = document.querySelector(".card");
const details = document.querySelector(".details");
const time = document.querySelector("img.time");
const icon = document.querySelector(".icon img");
const updateUI = (data) =>
{
const cityDets = data.cityDets;
const weather = data.weather;
// update details template
details.innerHTML =
`
<h5 class="my-3">${cityDets.EnglishName}</h5>
<div class="my-3">${weather.WeatherText}</h5>
<div class="display-4 my-4"
<span>${weather.Temperature.Imperial.Value}</span>
<span>°F</span>
</div>
`;
// update the night/day & icon images
const iconSrc = `img/icons/${weather.WeatherIcon}.svg`;
icon.setAttribute("src", iconSrc);
let timeSrc = null;
if (weather.IsDayTime)
{
timeSrc = "img/day.svg";
} else
{
timeSrc = "img/night.svg";
}
time.setAttribute("src", timeSrc);
// remove the d-none class if present
if (card.classList.contains("d-none"))
{
card.classList.remove("d-none");
}
};
const updateCity = async (city) =>
{
const cityDets = await getCity(city);
const weather = await getWeather(cityDets.Key);
}
return
{
cityDets: cityDets,
weather: weather,
};
cityForm.addEventListener("submit", (e) => {
// prevent default action
e.preventDefault();
// get city value
const city = cityForm.city.value.trim();
cityForm.reset();
// update the ui with new city
updateCity(city)
.then((data) => updateUI(data))
.catch((err) => console.log(err));
});
Summary
When a user submits the city name through a form, the application fetches the city’s weather details and updates the UI accordingly. The UI displays the city’s name, weather conditions, temperature, and changes the background image to reflect day or night based on the weather data.
Code Structure
- DOM Elements Selection:
- cityForm: The form element where users input the city name.
- card: The card element that displays the weather information.
- details: The element that holds the weather details.
- time: The image element that shows day or night background.
- icon: The image element that displays the weather icon.
- Functions:
- updateUI(data): Updates the UI.
- Updates the weather details template.
- Sets the weather icon.
- Sets the background image to day or night.
- Removes the d-none class from the card if present.
- updateCity(city): Fetches the city details and weather information asynchronously.
- Calls getCity(city) to get city details.
- Calls getWeather(cityDets.Key) to get weather information.
- Returns an object containing city details and weather data.
- updateUI(data): Updates the UI.
- Event Listener:
- Listens for the form submission.
- Prevents the default form submission action.
- Gets the city value from the form input.
- Resets the form.
- Calls updateCity(city) to fetch and update the UI with the new city’s weather data.
- Handles any errors that occur during the fetch process.
- Listens for the form submission.