/
grafula
/
javascript
Обзор
Документация
Войти
/
grafula
/
javascript
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
weather-app/script.js
146 строк
5 KB
Dar
Initial commit
19 дек 2025, 04:20
19 дек 2025, 04:20
a579753
Код
Авторство
О чём код?
const locationInput = document.querySelector('.location-input'); const locationButton = document.querySelector('.location-button'); const currentWeatherIcon = document.querySelector('.current-weather-icon'); const currentWeatherTemp = document.querySelector('.current-weather-temperature'); const currentWeatherStatus = document.querySelector('.current-weather-status'); const forecastElements = document.querySelectorAll('.forecast-element'); const currentWeatherContainer = document.querySelector('.current-weather'); const forecastContainer = document.querySelector('.forecast'); async function getCurrentWeather(city) { try { const response = await fetch( `https://api.weatherapi.com/v1/current.json?key=c436f8a6c83d4ed2862235930251812&q=${encodeURIComponent(city)}&aqi=no&lang=ru` ); if (!response.ok) { throw new Error('Город не найден'); } return await response.json(); } catch (error) { console.error('Ошибка:', error); alert('Не удалось получить данные о погоде. Проверьте название города.'); return null; } } async function getForecast(city) { try { const response = await fetch( `https://api.weatherapi.com/v1/forecast.json?key=c436f8a6c83d4ed2862235930251812&q=${encodeURIComponent(city)}&days=1&aqi=no&alerts=no&lang=ru` ); if (!response.ok) { throw new Error('Город не найден'); } return await response.json(); } catch (error) { console.error('Ошибка:', error); return null; } } function updateCurrentWeather(data) { if (!data) return; currentWeatherIcon.src = `https:${data.current.condition.icon}`; currentWeatherIcon.alt = data.current.condition.text; currentWeatherTemp.textContent = `${Math.round(data.current.temp_c)}°C`; currentWeatherStatus.textContent = data.current.condition.text; const cityName = data.location.name; const countryName = data.location.country; locationInput.placeholder = `${cityName}, ${countryName}`; locationInput.value = ''; currentWeatherContainer.style.display = 'flex'; } function updateForecast(data) { if (!data) return; const forecastHours = data.forecast.forecastday[0].hour; const timePoints = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]; forecastElements.forEach((element, index) => { if (index < timePoints.length) { const hourIndex = timePoints[index]; const hourData = forecastHours[hourIndex]; const timeElement = element.querySelector('.forecast-time'); const iconElement = element.querySelector('.forecast-icon'); const tempElement = element.querySelector('.forecast-temperature'); const date = new Date(hourData.time); const hours = date.getHours().toString().padStart(2, '0'); if (index === 0) { timeElement.textContent = '0:00'; } else { timeElement.textContent = `${hours}:00`; } iconElement.src = `https:${hourData.condition.icon}`; iconElement.alt = hourData.condition.text; tempElement.textContent = `${Math.round(hourData.temp_c)}°C`; } }); forecastContainer.style.display = 'flex'; } async function searchWeather() { const city = locationInput.value.trim(); if (!city) { alert('Пожалуйста, введите название города'); return; } const originalText = locationButton.innerHTML; locationButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i>'; locationButton.disabled = true; try { const [currentData, forecastData] = await Promise.all([ getCurrentWeather(city), getForecast(city) ]); if (currentData && forecastData) { updateCurrentWeather(currentData); updateForecast(forecastData); } } catch (error) { console.error('Ошибка при загрузке данных:', error); } finally { locationButton.innerHTML = originalText; locationButton.disabled = false; } } locationButton.addEventListener('click', searchWeather); locationInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') { searchWeather(); } }); window.addEventListener('DOMContentLoaded', async () => { locationInput.value = ''; }); setInterval(() => { const currentPlaceholder = locationInput.placeholder; if (currentPlaceholder !== 'Введите город') { const city = currentPlaceholder.split(',')[0].trim(); if (city) { locationInput.value = city; searchWeather(); } } }, 30 * 60 * 1000);