Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions projects/weather/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,16 @@
<body>
<main>
<h1>Weather</h1>
<form id="form"><input id="city" placeholder="Enter city" required> <button>Get</button></form>
<form id="form">
<div class="controls">
<input id="city" placeholder="Enter city" required>
<button type="submit">Get</button>
<button type="button" class="btn-secondary btn-icon" id="geoBtn" title="Use my location">📍</button>
<button type="button" class="btn-secondary btn-icon" id="unitBtn" title="Toggle units">°C</button>
</div>
</form>
<div id="out"></div>
<p class="notes">Use a public API; add icons, units, and caching.</p>
<p class="notes">Weather data cached for 30 minutes. Click 📍 for your location.</p>
</main>
<script type="module" src="./main.js"></script>
</body>
Expand Down
186 changes: 183 additions & 3 deletions projects/weather/main.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,185 @@
const form = document.getElementById('form'); const city = document.getElementById('city'); const out = document.getElementById('out');
const form = document.getElementById('form');
const city = document.getElementById('city');
const out = document.getElementById('out');
const geoBtn = document.getElementById('geoBtn');
const unitBtn = document.getElementById('unitBtn');

// State
let unit = 'C'; // C or F
const cache = {};
const CACHE_DURATION = 30 * 60 * 1000; // 30 minutes

// Weather icons mapping
const weatherIcons = {
'Sunny': '☀️',
'Clear': '🌙',
'Partly cloudy': '⛅',
'Cloudy': '☁️',
'Overcast': '☁️',
'Mist': '🌫️',
'Fog': '🌫️',
'Light rain': '🌦️',
'Moderate rain': '🌧️',
'Heavy rain': '🌧️',
'Light snow': '🌨️',
'Moderate snow': '❄️',
'Heavy snow': '❄️',
'Thunderstorm': '⛈️',
'default': '🌤️'
};

function getWeatherIcon(desc) {
for (const [key, icon] of Object.entries(weatherIcons)) {
if (desc.includes(key)) return icon;
}
return weatherIcons.default;
}

function getCacheKey(cityName) {
return `weather_${cityName.toLowerCase()}`;
}

function isCacheValid(timestamp) {
return Date.now() - timestamp < CACHE_DURATION;
}

function convertTemp(tempC) {
if (unit === 'F') {
return Math.round(tempC * 9 / 5 + 32);
}
return tempC;
}

function displayWeather(data, cityName) {
const cur = data.current_condition?.[0];
if (!cur) {
out.innerHTML = '<div class="error">No weather data available</div>';
return;
}

const desc = cur.weatherDesc?.[0]?.value || 'Unknown';
const icon = getWeatherIcon(desc);
const temp = convertTemp(parseInt(cur.temp_C));
const feelsLike = convertTemp(parseInt(cur.FeelsLikeC));
const unitSymbol = unit === 'C' ? '°C' : '°F';

const cacheKey = getCacheKey(cityName);
const cacheTime = cache[cacheKey]?.timestamp
? new Date(cache[cacheKey].timestamp).toLocaleTimeString()
: 'just now';

out.innerHTML = `
<div class="weather-card">
<div class="weather-header">
<div>
<h2 class="weather-city">${cityName}</h2>
<p class="weather-desc">${desc}</p>
</div>
<div class="weather-icon">${icon}</div>
</div>
<div class="weather-temp">${temp}${unitSymbol}</div>
<div class="weather-details">
<div class="detail-item">
<span class="detail-label">Feels like</span>
<span class="detail-value">${feelsLike}${unitSymbol}</span>
</div>
<div class="detail-item">
<span class="detail-label">Humidity</span>
<span class="detail-value">${cur.humidity}%</span>
</div>
<div class="detail-item">
<span class="detail-label">Wind</span>
<span class="detail-value">${cur.windspeedKmph} km/h</span>
</div>
<div class="detail-item">
<span class="detail-label">Pressure</span>
<span class="detail-value">${cur.pressure} mb</span>
</div>
</div>
<div class="cache-info">Last updated: ${cacheTime}</div>
</div>
`;
}

async function fetchWeather(cityName) {
const cacheKey = getCacheKey(cityName);

// Check cache
if (cache[cacheKey] && isCacheValid(cache[cacheKey].timestamp)) {
displayWeather(cache[cacheKey].data, cityName);
return;
}

out.innerHTML = '<div class="loading">Loading weather data...</div>';

try {
const q = encodeURIComponent(cityName);
const res = await fetch(`https://wttr.in/${q}?format=j1`);

if (!res.ok) {
throw new Error(`Failed to fetch: ${res.status}`);
}

const data = await res.json();

// Cache the result
cache[cacheKey] = {
data: data,
timestamp: Date.now()
};

displayWeather(data, cityName);
} catch (err) {
out.innerHTML = `<div class="error">Failed to fetch weather data. Please check the city name and try again.</div>`;
console.error(err);
}
}

// Form submit handler
form.addEventListener('submit', async e => {
e.preventDefault(); out.textContent = 'Loading...'; try { const q = encodeURIComponent(city.value); const res = await fetch(`https://wttr.in/${q}?format=j1`); const data = await res.json(); const cur = data.current_condition?.[0]; out.innerHTML = cur ? `<strong>${city.value}</strong>: ${cur.temp_C}°C, ${cur.weatherDesc?.[0]?.value}` : 'No data'; } catch (err) { out.textContent = 'Failed to fetch weather'; }
e.preventDefault();
const cityName = city.value.trim();
if (cityName) {
await fetchWeather(cityName);
}
});
// TODOs: use icons; toggle units; cache; geolocation; error states

// Geolocation handler
geoBtn.addEventListener('click', async () => {
if (!navigator.geolocation) {
out.innerHTML = '<div class="error">Geolocation is not supported by your browser</div>';
return;
}

geoBtn.disabled = true;
out.innerHTML = '<div class="loading">Getting your location...</div>';

navigator.geolocation.getCurrentPosition(
async (position) => {
const { latitude, longitude } = position.coords;
const cityName = `${latitude},${longitude}`;
city.value = 'My Location';
await fetchWeather(cityName);
geoBtn.disabled = false;
},
(error) => {
out.innerHTML = `<div class="error">Unable to get location: ${error.message}</div>`;
geoBtn.disabled = false;
}
);
});

// Unit toggle handler
unitBtn.addEventListener('click', () => {
unit = unit === 'C' ? 'F' : 'C';
unitBtn.textContent = `°${unit}`;

// Re-render current weather if exists
const currentCity = city.value.trim();
if (currentCity) {
const cacheKey = getCacheKey(currentCity);
if (cache[cacheKey]) {
displayWeather(cache[cacheKey].data, currentCity);
}
}
});
143 changes: 132 additions & 11 deletions projects/weather/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -5,42 +5,163 @@ body {
margin: 0;
padding: 2rem;
display: grid;
place-items: center
place-items: center;
min-height: 100vh;
}

main {
max-width: 560px;
width: 100%
width: 100%;
}

h1 {
margin: 0 0 1.5rem;
}

.controls {
display: flex;
gap: 0.5rem;
margin-bottom: 1rem;
}

input,
button {
font: inherit
font: inherit;
}

input {
padding: .5rem .75rem;
border-radius: .5rem;
padding: 0.5rem 0.75rem;
border-radius: 0.5rem;
border: 1px solid #262631;
background: #17171c;
color: #eef1f8
color: #eef1f8;
flex: 1;
}

input::placeholder {
color: #6b7280;
}

button {
background: #6ee7b7;
color: #0b1020;
border: none;
padding: .5rem .75rem;
border-radius: .5rem;
padding: 0.5rem 0.75rem;
border-radius: 0.5rem;
font-weight: 600;
cursor: pointer
cursor: pointer;
transition: background 0.2s;
}

button:hover {
background: #5dd6a5;
}

button:disabled {
opacity: 0.5;
cursor: not-allowed;
}

.btn-secondary {
background: #374151;
color: #eef1f8;
}

.btn-secondary:hover {
background: #4b5563;
}

.btn-icon {
padding: 0.5rem;
min-width: 38px;
}

#out {
margin-top: 1rem
margin-top: 1.5rem;
min-height: 100px;
}

.weather-card {
background: #17171c;
border: 1px solid #262631;
border-radius: 1rem;
padding: 1.5rem;
}

.weather-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: 1rem;
}

.weather-city {
font-size: 1.5rem;
font-weight: 600;
margin: 0;
}

.weather-icon {
font-size: 3rem;
}

.weather-temp {
font-size: 3rem;
font-weight: 700;
margin: 0.5rem 0;
}

.weather-desc {
font-size: 1.125rem;
color: #a6adbb;
margin: 0 0 1rem;
}

.weather-details {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
gap: 1rem;
padding-top: 1rem;
border-top: 1px solid #262631;
}

.detail-item {
display: flex;
flex-direction: column;
gap: 0.25rem;
}

.detail-label {
font-size: 0.875rem;
color: #6b7280;
}

.detail-value {
font-size: 1.125rem;
font-weight: 600;
}

.error {
background: #991b1b;
color: #fecaca;
padding: 1rem;
border-radius: 0.5rem;
}

.loading {
text-align: center;
color: #6b7280;
padding: 2rem;
}

.notes {
color: #a6adbb;
font-size: .9rem
font-size: 0.9rem;
margin-top: 1rem;
}

.cache-info {
font-size: 0.75rem;
color: #6b7280;
margin-top: 0.5rem;
}
Loading