CodingNic

Dynamic Weather Themes & Icons

Apply Theme and Current Icon During Rendering

Dynamic Weather Themes & Icons 25 min read

Apply Theme and Current Icon During Rendering

Apply Theme and Current Icon During Rendering

Task

Make the current-weather renderer update the body theme and main weather icon whenever new data arrives.

Open

Update applyTheme() to set the icon, then call it at the start of displayCurrent().

Implementation

javascript
function applyTheme(data) {
  document.body.className = "";
  const id = data.weather[0].id;
  const icon = data.weather[0].icon || "";
  const night = icon.endsWith("n");

  let theme = "clear";
  if (id >= 200 && id < 300) theme = "storm";
  else if (id >= 300 && id < 600) theme = "rain";
  else if (id >= 600 && id < 700) theme = "snow";
  else if (id >= 801 && id <= 804) theme = "clouds";
  else if (id === 800 && night) theme = "night";

  document.body.classList.add(`theme-${theme}`);
  $("weatherEmoji").innerHTML = weatherIconHTML(id, night);
}

function displayCurrent(data) {
  state.lastData = data;
  applyTheme(data);
  // keep the existing field rendering below...
}

Putting visual-state selection inside the current renderer guarantees every successful search refreshes the theme and icon at the same moment as the weather text.

Test

Search for a city and inspect both the current icon and body class. Confirm the two change together when the returned condition changes.

Expected result

Current weather data now controls the main icon and theme.

Checkpoint

Before moving on, confirm the expected result in the running app and make sure the browser console has no blocking errors.