CodingNic

Temperature Units & Persistent Preferences

Implement the Unit Toggle

Temperature Units & Persistent Preferences 15 min read

Implement the Unit Toggle

Implement the Unit Toggle

Task

Make the top-right button update state.unit and persist the choice.

Open

Add the listener near the bottom of script.js.

Implementation

javascript
$("unitToggle").addEventListener("click", async () => {
  state.unit = state.unit === "metric" ? "imperial" : "metric";
  localStorage.setItem("weatherUnit", state.unit);
  $("unitToggle").textContent = state.unit === "metric" ? "°C" : "°F";
});

$("unitToggle").textContent = state.unit === "metric" ? "°C" : "°F";

The state value uses the same metric/imperial names expected by OpenWeatherMap. localStorage makes the preference survive a page reload, while the button text provides immediate feedback.

Test

Click the toggle several times. Refresh the page and verify the last selected label returns.

Expected result

The unit control has persistent state.

Checkpoint

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