examples
dynamic
- change font size
- color picker
- compare random function performance
- counter (using innerHTML)
- counter (using a data attribute)
- counter (using a variable)
- deck filter
- weather report
- met museum search
- plus/minus
- track last button clicked
progressive enhancement
weather report
Loading weather report...
html
<div data-r="weatherError">
<select data-s="changeStation" data-r="loadStations" data-listen="input"></select>
<div data-r="weather">Loading weather report...</div>
</div>
<script data-template="option" type="text/html">
<option value="__CODE__">__ABBREVIATION__: __CITY__, __STATE__ [__CODE__]</option>
</script>
<script data-template="weather" type="text/html">
<div>__DESCRIPTION__</div>
<div>__TEMP__</div>
<img src="__IMG_SRC__" alt="__DESCRIPTION__ weather icon" />
</script> javascript
export const b = { init: "loadStations" };
let current_station;
let stations;
const stationsURL = `/versions/8/0/0/examples/dynamic/get-weather/stations.json`;
export function changeStation(ev, __, ___) {
current_station = ev.target.value;
b.trigger("weather");
}
export async function loadStations(_, __, el) {
stations = await b.getData(stationsURL);
if (stations) {
el.replaceChildren(...options());
b.trigger("weather");
} else {
b.trigger("weatherError");
}
}
function options() {
return Object.keys(stations)
.map((state, index) => {
if (index === 0) {
current_station = stationId(state);
}
const subs = {
__ABBREVIATION__: state,
__CITY__: cityName(state),
__CODE__: stationId(state),
__STATE__: stateName(state),
};
return b.render("option", subs);
});
}
export async function weather(_, __, el) {
el.innerHTML = "Loading weather report...";
const report = await b.getData(reportURL());
if (report === undefined || weatherIcon(report) === null) {
el.innerHTML =
`Weather currently unavailable for station ${current_station}`;
return;
}
const subs = {
__DESCRIPTION__: weatherDescription(report),
__IMG_SRC__: weatherIcon(report),
__TEMP__: tempString(report),
};
el.replaceChildren(b.render("weather", subs));
}
export function weatherError(_, __, el) {
el.innerHTML = "Error: could not get weather data";
}
// Helpers
function cityName(state) {
return stations[state].city_name;
}
function reportURL() {
return `https://api.weather.gov/stations/${current_station}/observations/latest`;
}
function stationId(state) {
return stations[state].weather_station_id;
}
function stateName(state) {
return stations[state].state_name;
}
function tempC(report) {
return report.properties.temperature.value;
}
function tempF(report) {
return Math.round((report.properties.temperature.value * 9 / 5) + 32);
}
function tempString(report) {
return `${tempF(report)}°F (${tempC(report)}°C)`;
}
function weatherDescription(report) {
return report.properties.textDescription;
}
function weatherIcon(report) {
return report.properties.icon;
}styles
.example-block-2 {
min-height: 16rem;
}