Develop an interactive weather widget that fetches and displays real-time data from a…
- User
Develop an interactive weather widget that fetches and displays real-time data from a weather API using HTML, CSS, and JS.
Assistant
Develop an interactive weather widget that fetches and displays real-time data from a weather API using HTML, CSS, and JS.
The user wants an interactive weather widget that fetches real-time data from a weather API. Let me think about this:
Weather API: I'll use Open-Meteo API because it's free and doesn't require an API key - perfect for a demo. It provides real-time weather data.
Design approach: I need to avoid the generic/bland look. Let me think of a distinctive design:
Features:
Visual elements:
Typography:
Color scheme:
Interactions:
Let me create this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather Widget</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&family=DM+Sans:wght@400;500;600&display=swap" rel="stylesheet">
<style>
/* CSS variables and styles */
</style>
</head>
<body>
<!-- Widget content -->
<script>
// Weather API logic
</script>
</body>
</html>
Let me write the complete implementation now.
I'll create a visually striking weather widget with real-time data from Open-Meteo API (free, no API key required). The design features atmospheric depth with dynamic backgrounds that adapt to weather conditions.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather Widget</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&family=DM+Sans:opsz,wght@9..40,400;9..40,500;9..40,600&display=swap" rel="stylesheet">
<style>
:root {
--bg-primary: #0a0f1a;
--bg-secondary: #111827;
--fg-primary: #f1f5f9;
--fg-secondary: #94a3b8;
--accent: #3b82f6;
--accent-glow: rgba(59, 130, 246, 0.4);
--card-bg: rgba(17, 24, 39, 0.7);
--border: rgba(148, 163, 184, 0.1);
--glass: rgba(255, 255, 255, 0.03);
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'DM Sans', sans-serif;
background: var(--bg-primary);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 1rem;
overflow-x: hidden;
}
.headline-font {
font-family: 'Space Grotesk', sans-serif;
}
/* Atmospheric background */
.atmosphere {
position: fixed;
inset: 0;
z-index: 0;
overflow: hidden;
transition: all 1.5s ease;
}
.atmosphere::before {
content: '';
position: absolute;
top: -50%;
left: -50%;
width: 200%;
height: 200%;
background:
radial-gradient(ellipse at 30% 20%, var(--accent-glow) 0%, transparent 50%),
radial-gradient(ellipse at 70% 80%, rgba(139, 92, 246, 0.2) 0%, transparent 40%);
animation: drift 20s ease-in-out infinite;
}
@keyframes drift {
0%, 100% { transform: translate(0, 0) rotate(0deg); }
50% { transform: translate(-5%, 5%) rotate(5deg); }
}
.atmosphere.sunny {
background: linear-gradient(135deg, #1a1c2e 0%, #2d1f3d 50%, #1a1c2e 100%);
}
.atmosphere.sunny::before {
background:
radial-gradient(ellipse at 70% 20%, rgba(251, 191, 36, 0.3) 0%, transparent 40%),
radial-gradient(ellipse at 30% 70%, rgba(251, 146, 60, 0.15) 0%, transparent 50%);
}
.atmosphere.rainy {
background: linear-gradient(180deg, #0f172a 0%, #1e293b 50%, #0f172a 100%);
}
.atmosphere.rainy::before {
background:
radial-gradient(ellipse at 50% 0%, rgba(59, 130, 246, 0.3) 0%, transparent 60%),
radial-gradient(ellipse at 20% 100%, rgba(99, 102, 241, 0.2) 0%, transparent 40%);
}
.atmosphere.cloudy {
background: linear-gradient(180deg, #1f2937 0%, #374151 50%, #1f2937 100%);
}
.atmosphere.cloudy::before {
background:
radial-gradient(ellipse at 40% 30%, rgba(156, 163, 175, 0.2) 0%, transparent 50%),
radial-gradient(ellipse at 60% 70%, rgba(107, 114, 128, 0.15) 0%, transparent 40%);
}
.atmosphere.snowy {
background: linear-gradient(135deg, #1e293b 0%, #334155 50%, #1e293b 100%);
}
.atmosphere.snowy::before {
background:
radial-gradient(ellipse at 30% 20%, rgba(226, 232, 240, 0.2) 0%, transparent 40%),
radial-gradient(ellipse at 70% 80%, rgba(203, 213, 225, 0.15) 0%, transparent 50%);
}
/* Noise overlay */
.noise {
position: fixed;
inset: 0;
z-index: 1;
opacity: 0.03;
pointer-events: none;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E");
}
/* Widget container */
.widget {
position: relative;
z-index: 10;
width: 100%;
max-width: 420px;
background: var(--card-bg);
backdrop-filter: blur(20px);
border: 1px solid var(--border);
border-radius: 24px;
overflow: hidden;
box-shadow:
0 25px 50px -12px rgba(0, 0, 0, 0.5),
0 0 0 1px rgba(255, 255, 255, 0.05) inset;
}
/* Search input */
.search-container {
position: relative;
padding: 1.5rem;
border-bottom: 1px solid var(--border);
}
.search-input {
width: 100%;
padding: 0.875rem 1rem 0.875rem 3rem;
background: var(--glass);
border: 1px solid var(--border);
border-radius: 12px;
color: var(--fg-primary);
font-size: 0.9375rem;
font-family: inherit;
transition: all 0.3s ease;
}
.search-input::placeholder {
color: var(--fg-secondary);
}
.search-input:focus {
outline: none;
border-color: var(--accent);
box-shadow: 0 0 0 3px var(--accent-glow);
}
.search-icon {
position: absolute;
left: 2.5rem;
top: 50%;
transform: translateY(-50%);
color: var(--fg-secondary);
pointer-events: none;
}
.search-btn {
position: absolute;
right: 2rem;
top: 50%;
transform: translateY(-50%);
padding: 0.5rem 1rem;
background: var(--accent);
border: none;
border-radius: 8px;
color: white;
font-size: 0.875rem;
font-weight: 500;
cursor: pointer;
transition: all 0.2s ease;
}
.search-btn:hover {
background: #2563eb;
transform: translateY(-50%) scale(1.02);
}
.search-btn:active {
transform: translateY(-50%) scale(0.98);
}
/* Suggestions dropdown */
.suggestions {
position: absolute;
top: 100%;
left: 1.5rem;
right: 1.5rem;
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 12px;
margin-top: 0.5rem;
overflow: hidden;
z-index: 100;
display: none;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
}
.suggestions.active {
display: block;
}
.suggestion-item {
padding: 0.875rem 1rem;
cursor: pointer;
transition: background 0.2s ease;
border-bottom: 1px solid var(--border);
}
.suggestion-item:last-child {
border-bottom: none;
}
.suggestion-item:hover {
background: var(--glass);
}
.suggestion-item .city {
color: var(--fg-primary);
font-weight: 500;
}
.suggestion-item .country {
color: var(--fg-secondary);
font-size: 0.8125rem;
margin-top: 0.125rem;
}
/* Main weather display */
.weather-main {
padding: 2rem 1.5rem;
text-align: center;
}
.location {
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
margin-bottom: 0.5rem;
}
.location svg {
width: 18px;
height: 18px;
color: var(--accent);
}
.location-name {
font-size: 1.25rem;
font-weight: 600;
color: var(--fg-primary);
}
.location-country {
color: var(--fg-secondary);
font-size: 0.875rem;
}
.weather-icon-container {
position: relative;
width: 140px;
height: 140px;
margin: 1.5rem auto;
}
.weather-icon {
width: 100%;
height: 100%;
object-fit: contain;
filter: drop-shadow(0 10px 30px var(--accent-glow));
}
/* Animated weather icons */
.icon-sunny {
animation: pulse-glow 3s ease-in-out infinite;
}
@keyframes pulse-glow {
0%, 100% { filter: drop-shadow(0 10px 30px rgba(251, 191, 36, 0.4)); }
50% { filter: drop-shadow(0 10px 50px rgba(251, 191, 36, 0.6)); }
}
.icon-rainy {
animation: rain-bounce 2s ease-in-out infinite;
}
@keyframes rain-bounce {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-5px); }
}
.icon-cloudy {
animation: cloud-drift 4s ease-in-out infinite;
}
@keyframes cloud-drift {
0%, 100% { transform: translateX(0); }
50% { transform: translateX(10px); }
}
.temperature {
font-family: 'Space Grotesk', sans-serif;
font-size: 5rem;
font-weight: 300;
line-height: 1;
color: var(--fg-primary);
margin-bottom: 0.5rem;
letter-spacing: -0.02em;
}
.temperature .degree {
font-size: 2.5rem;
font-weight: 400;
vertical-align: super;
color: var(--fg-secondary);
}
.condition {
font-size: 1.125rem;
color: var(--fg-secondary);
text-transform: capitalize;
margin-bottom: 1.5rem;
}
/* Stats row */
.stats {
display: flex;
justify-content: center;
gap: 2rem;
padding: 1.25rem;
background: var(--glass);
border-radius: 16px;
margin: 0 0.5rem;
}
.stat {
text-align: center;
}
.stat-icon {
width: 20px;
height: 20px;
color: var(--accent);
margin: 0 auto 0.375rem;
}
.stat-value {
font-family: 'Space Grotesk', sans-serif;
font-size: 1.125rem;
font-weight: 600;
color: var(--fg-primary);
}
.stat-label {
font-size: 0.75rem;
color: var(--fg-secondary);
text-transform: uppercase;
letter-spacing: 0.05em;
}
/* Forecast section */
.forecast {
padding: 1.25rem 1.5rem;
border-top: 1px solid var(--border);
}
.forecast-title {
font-size: 0.75rem;
color: var(--fg-secondary);
text-transform: uppercase;
letter-spacing: 0.1em;
margin-bottom: 1rem;
}
.forecast-list {
display: flex;
gap: 0.5rem;
overflow-x: auto;
padding-bottom: 0.5rem;
scrollbar-width: none;
}
.forecast-list::-webkit-scrollbar {
display: none;
}
.forecast-item {
flex: 0 0 auto;
width: 72px;
padding: 1rem 0.75rem;
background: var(--glass);
border: 1px solid var(--border);
border-radius: 16px;
text-align: center;
cursor: pointer;
transition: all 0.3s ease;
}
.forecast-item:hover {
background: rgba(59, 130, 246, 0.1);
border-color: var(--accent);
transform: translateY(-4px);
}
.forecast-item.active {
background: rgba(59, 130, 246, 0.15);
border-color: var(--accent);
}
.forecast-day {
font-size: 0.75rem;
color: var(--fg-secondary);
margin-bottom: 0.625rem;
font-weight: 500;
}
.forecast-icon {
width: 32px;
height: 32px;
margin: 0 auto 0.625rem;
}
.forecast-temp {
font-family: 'Space Grotesk', sans-serif;
font-size: 1rem;
font-weight: 600;
color: var(--fg-primary);
}
.forecast-temp-low {
font-size: 0.8125rem;
color: var(--fg-secondary);
font-weight: 400;
}
/* Loading state */
.loading {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 4rem 2rem;
}
.spinner {
width: 48px;
height: 48px;
border: 3px solid var(--border);
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.loading-text {
margin-top: 1rem;
color: var(--fg-secondary);
font-size: 0.875rem;
}
/* Error state */
.error-state {
text-align: center;
padding: 3rem 2rem;
}
.error-icon {
width: 48px;
height: 48px;
color: #ef4444;
margin: 0 auto 1rem;
}
.error-text {
color: var(--fg-secondary);
margin-bottom: 1rem;
}
.retry-btn {
padding: 0.75rem 1.5rem;
background: var(--accent);
border: none;
border-radius: 10px;
color: white;
font-weight: 500;
cursor: pointer;
transition: all 0.2s ease;
}
.retry-btn:hover {
background: #2563eb;
}
/* Entrance animations */
.fade-in {
animation: fadeIn 0.6s ease forwards;
}
.slide-up {
animation: slideUp 0.6s ease forwards;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.stagger-1 { animation-delay: 0.1s; opacity: 0; }
.stagger-2 { animation-delay: 0.2s; opacity: 0; }
.stagger-3 { animation-delay: 0.3s; opacity: 0; }
.stagger-4 { animation-delay: 0.4s; opacity: 0; }
/* Reduced motion */
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}
/* Mobile adjustments */
@media (max-width: 480px) {
.widget {
border-radius: 20px;
}
.temperature {
font-size: 4rem;
}
.weather-icon-container {
width: 120px;
height: 120px;
}
.stats {
gap: 1rem;
}
}
/* Focus visible */
button:focus-visible,
input:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
</style>
</head>
<body>
<div class="atmosphere" id="atmosphere"></div>
<div class="noise"></div>
<div class="widget">
<!-- Search -->
<div class="search-container">
<svg class="search-icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="11" cy="11" r="8"/>
<path d="m21 21-4.3-4.3"/>
</svg>
<input
type="text"
class="search-input"
id="searchInput"
placeholder="Search city..."
autocomplete="off"
aria-label="Search for a city"
>
<button class="search-btn" id="searchBtn" aria-label="Search">Go</button>
<div class="suggestions" id="suggestions" role="listbox"></div>
</div>
<!-- Weather Content -->
<div id="weatherContent">
<div class="loading">
<div class="spinner"></div>
<p class="loading-text">Fetching weather data...</p>
</div>
</div>
</div>
<script>
// Weather codes mapping
const weatherCodes = {
0: { condition: 'Clear sky', icon: 'sunny', atmosphere: 'sunny' },
1: { condition: 'Mainly clear', icon: 'sunny', atmosphere: 'sunny' },
2: { condition: 'Partly cloudy', icon: 'partly-cloudy', atmosphere: 'cloudy' },
3: { condition: 'Overcast', icon: 'cloudy', atmosphere: 'cloudy' },
45: { condition: 'Foggy', icon: 'foggy', atmosphere: 'cloudy' },
48: { condition: 'Depositing rime fog', icon: 'foggy', atmosphere: 'cloudy' },
51: { condition: 'Light drizzle', icon: 'rainy', atmosphere: 'rainy' },
53: { condition: 'Moderate drizzle', icon: 'rainy', atmosphere: 'rainy' },
55: { condition: 'Dense drizzle', icon: 'rainy', atmosphere: 'rainy' },
61: { condition: 'Slight rain', icon: 'rainy', atmosphere: 'rainy' },
63: { condition: 'Moderate rain', icon: 'rainy', atmosphere: 'rainy' },
65: { condition: 'Heavy rain', icon: 'rainy', atmosphere: 'rainy' },
71: { condition: 'Slight snow', icon: 'snowy', atmosphere: 'snowy' },
73: { condition: 'Moderate snow', icon: 'snowy', atmosphere: 'snowy' },
75: { condition: 'Heavy snow', icon: 'snowy', atmosphere: 'snowy' },
77: { condition: 'Snow grains', icon: 'snowy', atmosphere: 'snowy' },
80: { condition: 'Slight rain showers', icon: 'rainy', atmosphere: 'rainy' },
81: { condition: 'Moderate rain showers', icon: 'rainy', atmosphere: 'rainy' },
82: { condition: 'Violent rain showers', icon: 'rainy', atmosphere: 'rainy' },
85: { condition: 'Slight snow showers', icon: 'snowy', atmosphere: 'snowy' },
86: { condition: 'Heavy snow showers', icon: 'snowy', atmosphere: 'snowy' },
95: { condition: 'Thunderstorm', icon: 'thunderstorm', atmosphere: 'rainy' },
96: { condition: 'Thunderstorm with hail', icon: 'thunderstorm', atmosphere: 'rainy' },
99: { condition: 'Thunderstorm with heavy hail', icon: 'thunderstorm', atmosphere: 'rainy' }
};
// SVG Icons
const weatherIcons = {
sunny: `<svg viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="32" cy="32" r="14" fill="url(#sunGrad)" class="icon-sunny"/>
<g stroke="#fbbf24" stroke-width="3" stroke-linecap="round">
<line x1="32" y1="4" x2="32" y2="12"/>
<line x1="32" y1="52" x2="32" y2="60"/>
<line x1="4" y1="32" x2="12" y2="32"/>
<line x1="52" y1="32" x2="60" y2="32"/>
<line x1="12.2" y1="12.2" x2="17.9" y2="17.9"/>
<line x1="46.1" y1="46.1" x2="51.8" y2="51.8"/>
<line x1="12.2" y1="51.8" x2="17.9" y2="46.1"/>
<line x1="46.1" y1="17.9" x2="51.8" y2="12.2"/>
</g>
<defs>
<radialGradient id="sunGrad" cx="0.5" cy="0.5" r="0.5">
<stop offset="0%" stop-color="#fef08a"/>
<stop offset="100%" stop-color="#f59e0b"/>
</radialGradient>
</defs>
</svg>`,
'partly-cloudy': `<svg viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="24" cy="24" r="10" fill="#fbbf24"/>
<path d="M44 48H20a12 12 0 0 1-2.4-23.76A10 10 0 0 1 36 22a14 14 0 0 1 8 26z" fill="url(#cloudGrad1)"/>
<defs>
<linearGradient id="cloudGrad1" x1="8" y1="48" x2="56" y2="48" gradientUnits="userSpaceOnUse">
<stop offset="0%" stop-color="#e2e8f0"/>
<stop offset="100%" stop-color="#94a3b8"/>
</linearGradient>
</defs>
</svg>`,
cloudy: `<svg viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg" class="icon-cloudy">
<path d="M50 52H18a14 14 0 0 1-2.8-27.72A12 12 0 0 1 38 20a16 16 0 0 1 12 32z" fill="url(#cloudGrad2)"/>
<defs>
<linearGradient id="cloudGrad2" x1="4" y1="52" x2="60" y2="52" gradientUnits="userSpaceOnUse">
<stop offset="0%" stop-color="#cbd5e1"/>
<stop offset="100%" stop-color="#64748b"/>
</linearGradient>
</defs>
</svg>`,
rainy: `<svg viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg" class="icon-rainy">
<path d="M48 36H16a12 12 0 0 1-2.4-23.76A10 10 0 0 1 32 10a14 14 0 0 1 16 26z" fill="url(#rainCloud)"/>
<g stroke="#3b82f6" stroke-width="2.5" stroke-linecap="round">
<line x1="20" y1="44" x2="16" y2="56"><animate attributeName="y2" values="56;52;56" dur="1s" repeatCount="indefinite"/></line>
<line x1="32" y1="44" x2="28" y2="56"><animate attributeName="y2" values="56;52;56" dur="1s" begin="0.2s" repeatCount="indefinite"/></line>
<line x1="44" y1="44" x2="40" y2="56"><animate attributeName="y2" values="56;52;56" dur="1s" begin="0.4s" repeatCount="indefinite"/></line>
</g>
<defs>
<linearGradient id="rainCloud" x1="4" y1="36" x2="56" y2="36" gradientUnits="userSpaceOnUse">
<stop offset="0%" stop-color="#64748b"/>
<stop offset="100%" stop-color="#475569"/>
</linearGradient>
</defs>
</svg>`,
snowy: `<svg viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M48 36H16a12 12 0 0 1-2.4-23.76A10 10 0 0 1 32 10a14 14 0 0 1 16 26z" fill="url(#snowCloud)"/>
<g fill="#e2e8f0">
<circle cx="18" cy="48" r="2.5"><animate attributeName="cy" values="48;52;48" dur="2s" repeatCount="indefinite"/></circle>
<circle cx="32" cy="50" r="3"><animate attributeName="cy" values="50;54;50" dur="2s" begin="0.3s" repeatCount="indefinite"/></circle>
<circle cx="46" cy="48" r="2.5"><animate attributeName="cy" values="48;52;48" dur="2s" begin="0.6s" repeatCount="indefinite"/></circle>
<circle cx="25" cy="56" r="2"><animate attributeName="cy" values="56;60;56" dur="2s" begin="0.9s" repeatCount="indefinite"/></circle>
<circle cx="39" cy="56" r="2"><animate attributeName="cy" values="56;60;56" dur="2s" begin="1.2s" repeatCount="indefinite"/></circle>
</g>
<defs>
<linearGradient id="snowCloud" x1="4" y1="36" x2="56" y2="36" gradientUnits="userSpaceOnUse">
<stop offset="0%" stop-color="#94a3b8"/>
<stop offset="100%" stop-color="#64748b"/>
</linearGradient>
</defs>
</svg>`,
foggy: `<svg viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
<g stroke="#94a3b8" stroke-width="4" stroke-linecap="round" opacity="0.6">
<line x1="8" y1="24" x2="56" y2="24"/>
<line x1="12" y1="34" x2="52" y2="34"/>
<line x1="8" y1="44" x2="56" y2="44"/>
<line x1="16" y1="54" x2="48" y2="54"/>
</g>
</svg>`,
thunderstorm: `<svg viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M48 32H16a12 12 0 0 1-2.4-23.76A10 10 0 0 1 32 6a14 14 0 0 1 16 26z" fill="url(#stormCloud)"/>
<path d="M36 32l-6 14h8l-4 14 12-18h-8l6-10h-8z" fill="#fbbf24">
<animate attributeName="opacity" values="1;0.6;1" dur="0.5s" repeatCount="indefinite"/>
</path>
<defs>
<linearGradient id="stormCloud" x1="4" y1="32" x2="56" y2="32" gradientUnits="userSpaceOnUse">
<stop offset="0%" stop-color="#374151"/>
<stop offset="100%" stop-color="#1f2937"/>
</linearGradient>
</defs>
</svg>`
};
// DOM elements - initialized after DOM ready
let searchInput, searchBtn, suggestionsEl, weatherContent, atmosphereEl;
// State
let currentWeatherData = null;
let searchTimeout = null;
// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
searchInput = document.getElementById('searchInput');
searchBtn = document.getElementById('searchBtn');
suggestionsEl = document.getElementById('suggestions');
weatherContent = document.getElementById('weatherContent');
atmosphereEl = document.getElementById('atmosphere');
// Event listeners
searchInput.addEventListener('input', handleSearchInput);
searchInput.addEventListener('keydown', handleKeydown);
searchBtn.addEventListener('click', handleSearch);
// Load default city
fetchWeatherByCity('Tokyo');
});
// Handle search input with debounce
function handleSearchInput(e) {
const query = e.target.value.trim();
if (searchTimeout) {
clearTimeout(searchTimeout);
}
if (query.length < 2) {
suggestionsEl.classList.remove('active');
return;
}
searchTimeout = setTimeout(() => {
fetchCitySuggestions(query);
}, 300);
}
// Handle keyboard navigation
function handleKeydown(e) {
if (e.key === 'Enter') {
e.preventDefault();
handleSearch();
} else if (e.key === 'Escape') {
suggestionsEl.classList.remove('active');
}
}
// Handle search button click
function handleSearch() {
const query = searchInput.value.trim();
if (query) {
suggestionsEl.classList.remove('active');
fetchWeatherByCity(query);
}
}
// Fetch city suggestions from API
async function fetchCitySuggestions(query) {
try {
const response = await fetch(
`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(query)}&count=5&language=en&format=json`
);
const data = await response.json();
if (data.results && data.results.length > 0) {
renderSuggestions(data.results);
} else {
suggestionsEl.classList.remove('active');
}
} catch (error) {
console.error('Error fetching suggestions:', error);
}
}
// Render suggestions dropdown
function renderSuggestions(cities) {
suggestionsEl.innerHTML = cities.map(city => `
<div class="suggestion-item" role="option" data-lat="${city.latitude}" data-lon="${city.longitude}" data-name="${city.name}" data-country="${city.country || ''}">
<div class="city">${city.name}</div>
<div class="country">${city.admin1 ? city.admin1 + ', ' : ''}${city.country || ''}</div>
</div>
`).join('');
suggestionsEl.classList.add('active');
// Add click handlers
suggestionsEl.querySelectorAll('.suggestion-item').forEach(item => {
item.addEventListener('click', () => {
const lat = parseFloat(item.dataset.lat);
const lon = parseFloat(item.dataset.lon);
const name = item.dataset.name;
const country = item.dataset.country;
searchInput.value = name;
suggestionsEl.classList.remove('active');
fetchWeather(lat, lon, name, country);
});
});
}
// Fetch weather by city name
async function fetchWeatherByCity(cityName) {
showLoading();
try {
const geoResponse = await fetch(
`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(cityName)}&count=1&language=en&format=json`
);
const geoData = await geoResponse.json();
if (!geoData.results || geoData.results.length === 0) {
showError('City not found. Please try another location.');
return;
}
const city = geoData.results[0];
fetchWeather(city.latitude, city.longitude, city.name, city.country);
} catch (error) {
showError('Unable to find location. Please try again.');
}
}
// Fetch weather data
async function fetchWeather(lat, lon, cityName, country) {
showLoading();
try {
const response = await fetch(
`https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lon}¤t=temperature_2m,relative_humidity_2m,weather_code,wind_speed_10m&daily=weather_code,temperature_2m_max,temperature_2m_min&timezone=auto&forecast_days=7`
);
const data = await response.json();
currentWeatherData = {
...data,
cityName,
country
};
renderWeather();
} catch (error) {
showError('Unable to fetch weather data. Please try again.');
}
}
// Show loading state
function showLoading() {
weatherContent.innerHTML = `
<div class="loading">
<div class="spinner"></div>
<p class="loading-text">Fetching weather data...</p>
</div>
`;
}
// Show error state
function showError(message) {
weatherContent.innerHTML = `
<div class="error-state">
<svg class="error-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="12" cy="12" r="10"/>
<line x1="12" y1="8" x2="12" y2="12"/>
<line x1="12" y1="16" x2="12.01" y2="16"/>
</svg>
<p class="error-text">${message}</p>
<button class="retry-btn" onclick="fetchWeatherByCity('${searchInput.value || 'Tokyo'}')">Try Again</button>
</div>
`;
}
// Render weather UI
function renderWeather() {
if (!currentWeatherData) return;
const { current, daily, cityName, country } = currentWeatherData;
const weatherInfo = weatherCodes[current.weather_code] || weatherCodes[0];
// Update atmosphere
atmosphereEl.className = 'atmosphere ' + weatherInfo.atmosphere;
// Get day names
const dayNames = daily.time.map(time => {
const date = new Date(time);
const today = new Date();
if (date.toDateString() === today.toDateString()) return 'Today';
if (date.toDateString() === new Date(today.setDate(today.getDate() + 1)).toDateString()) return 'Tomorrow';
return date.toLocaleDateString('en-US', { weekday: 'short' });
});
weatherContent.innerHTML = `
<!-- Main weather -->
<div class="weather-main">
<div class="location slide-up stagger-1">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/>
<circle cx="12" cy="10" r="3"/>
</svg>
<div>
<div class="location-name">${cityName}</div>
<div class="location-country">${country || ''}</div>
</div>
</div>
<div class="weather-icon-container slide-up stagger-2">
<div class="weather-icon">${weatherIcons[weatherInfo.icon]}</div>
</div>
<div class="temperature slide-up stagger-2">
${Math.round(current.temperature_2m)}<span class="degree">°</span>
</div>
<div class="condition slide-up stagger-3">${weatherInfo.condition}</div>
<div class="stats slide-up stagger-4">
<div class="stat">
<svg class="stat-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z"/>
</svg>
<div class="stat-value">${current.relative_humidity_2m}%</div>
<div class="stat-label">Humidity</div>
</div>
<div class="stat">
<svg class="stat-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M9.59 4.59A2 2 0 1 1 11 8H2m10.59 11.41A2 2 0 1 0 14 16H2m15.73-8.27A2.5 2.5 0 1 1 19.5 12H2"/>
</svg>
<div class="stat-value">${Math.round(current.wind_speed_10m)}</div>
<div class="stat-label">km/h</div>
</div>
<div class="stat">
<svg class="stat-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M14 14.76V3.5a2.5 2.5 0 0 0-5 0v11.26a4.5 4.5 0 1 0 5 0z"/>
</svg>
<div class="stat-value">${Math.round(daily.temperature_2m_max[0])}°</div>
<div class="stat-label">High</div>
</div>
</div>
</div>
<!-- Forecast -->
<div class="forecast fade-in" style="animation-delay: 0.5s; opacity: 0;">
<div class="forecast-title">7-Day Forecast</div>
<div class="forecast-list">
${daily.time.slice(0, 7).map((time, i) => {
const dayWeather = weatherCodes[daily.weather_code[i]] || weatherCodes[0];
return `
<div class="forecast-item ${i === 0 ? 'active' : ''}" data-index="${i}">
<div class="forecast-day">${dayNames[i]}</div>
<div class="forecast-icon">${weatherIcons[dayWeather.icon]}</div>
<div class="forecast-temp">
${Math.round(daily.temperature_2m_max[i])}°
<span class="forecast-temp-low">/ ${Math.round(daily.temperature_2m_min[i])}°</span>
</div>
</div>
`;
}).join('')}
</div>
</div>
`;
// Add forecast item interactions
document.querySelectorAll('.forecast-item').forEach(item => {
item.addEventListener('click', function() {
document.querySelectorAll('.forecast-item').forEach(el => el.classList.remove('active'));
this.classList.add('active');
});
});
}
</script>
</body>
</html>
prefers-reduced-motion