-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
182 lines (156 loc) · 5.91 KB
/
script.js
File metadata and controls
182 lines (156 loc) · 5.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
const cityInput = document.querySelector('.city-input');
const searchBtn = document.querySelector('.search-btn');
const suggestionsContainer = document.querySelector('.suggestions-container');
const apiKey = '12c2a4d4f50d89d9c509220bf8183ab0';
const notFound = document.querySelector('.not-found');
const searchCity = document.querySelector('.search-city');
const weatherInfo = document.querySelector('.weather-infos');
const countryName = document.querySelector('.country');
const tempText = document.querySelector('.temp-text');
const conditionText = document.querySelector('.condition-text');
const humidityValue = document.querySelector('.humidity-value-text');
const windSpeedValue = document.querySelector('.wind-value-text');
const weatherSummaryImg = document.querySelector('.weather-summary');
const currentDate = document.querySelector('.current-date');
const forecastItemContainer = document.querySelector('.forecast-items-container');
searchBtn.addEventListener('click', () => {
if (cityInput.value.trim() != ''){
updateWeatherInfo(cityInput.value);
cityInput.value = '';
cityInput.blur();
}
});
cityInput.addEventListener('keydown', (event) => {
if (event.key == 'Enter' && cityInput.value.trim() != '') {
updateWeatherInfo(cityInput.value);
cityInput.value = '';
cityInput.blur();
}
});
cityInput.addEventListener('input', async (e) => {
const inputValue = e.target.value.trim();
if (inputValue.length > 2) {
const suggestions = await fetchCitySuggestions(inputValue);
displaySuggestions(suggestions);
} else {
suggestionsContainer.style.display = 'none';
}
});
async function fetchCitySuggestions(query) {
try {
const response = await fetch(
`https://api.openweathermap.org/geo/1.0/direct?q=${query}&limit=5&appid=${apiKey}`
);
return await response.json();
} catch (error) {
console.error('Error fetching suggestions:', error);
return [];
}
};
function displaySuggestions(suggestions) {
if (suggestions.length === 0) {
suggestionsContainer.style.display = 'none';
return;
}
suggestionsContainer.innerHTML = '';
suggestions.forEach(suggestion => {
const suggestionItem = document.createElement('div');
suggestionItem.classList.add('suggestion-item');
suggestionItem.textContent = `${suggestion.name}`;
suggestionItem.addEventListener('click', () => {
cityInput.value = `${suggestion.name}`;
suggestionsContainer.style.display = 'none';
updateWeatherInfo(`${suggestion.name}`);
});
suggestionsContainer.appendChild(suggestionItem);
});
suggestionsContainer.style.display = 'block';
};
document.addEventListener('click', (e) => {
if (!e.target.closest('.input-container')) {
suggestionsContainer.style.display = 'none';
}
});
async function getFetchData(endPoint, city){
const apiUrl = `https://api.openweathermap.org/data/2.5/${endPoint}?q=${city}&appid=${apiKey}&units=metric`
const response = await fetch(apiUrl);
return response.json();
}
function getWeatherIcon(id) {
if (id >= 200 && id <= 232) return 'thunderstorm.svg';
if (id >= 300 && id <= 321) return 'drizzle.svg';
if (id >= 500 && id <= 531) return 'rain.svg';
if (id >= 600 && id <= 622) return 'snow.svg';
if (id >= 701 && id <= 781) return 'atmosphere.svg';
if (id === 800) return 'clear.svg';
if (id >= 801 && id <= 804) return 'clouds.svg';
return 'clouds.svg';
}
function getCurrentDate(){
const currentDate = new Date();
const options = {
weekday : 'short',
day : '2-digit',
month : 'short'
}
return currentDate.toLocaleDateString('en-DZ', options);
}
async function updateWeatherInfo (city) {
const weatherData = await getFetchData('weather', city);
if (weatherData.cod != 200){
showDisplaySection(notFound);
return;
}
const {
name : country,
main : {temp, humidity},
weather : [{id, main}],
wind : {speed}
} = weatherData;
countryName.textContent = country;
tempText.textContent = Math.round(temp) + ' ℃';
conditionText.textContent = main;
humidityValue.textContent = humidity + '%';
windSpeedValue.textContent = speed + ' M/s';
weatherSummaryImg.src = `assets/weather/${getWeatherIcon(id)}`;
currentDate.textContent = getCurrentDate();
await updateForecastsInfo(city);
showDisplaySection(weatherInfo);
}
async function updateForecastsInfo(city) {
const forecastsData = await getFetchData('forecast', city);
const timeTaken = '12:00:00';
const todayDate = new Date().toISOString().split('T')[0];
forecastItemContainer.innerHTML = '';
forecastsData.list.forEach(foreCastWeather => {
if (foreCastWeather.dt_txt.includes(timeTaken) && !foreCastWeather.dt_txt.includes(todayDate)){
updateForecastsItems(foreCastWeather);
}
});
}
function updateForecastsItems(weatherData) {
const {
dt_txt : date,
weather : [{id}],
main : {temp}
} = weatherData;
const dateTaken = new Date(date)
const dateOption = {
day : '2-digit',
month : 'short'
}
const dateResult = dateTaken.toLocaleDateString('en-DZ', dateOption);
console.log(weatherData);
const forecastItem = `
<div class="forecast-item">
<h5 class="forecast-item-date">${dateResult}</h5>
<img src="assets/weather/${getWeatherIcon(id)}" alt="Weather Image" class="forecast-item-img">
<h5 class="forecast-item-temp">${Math.round(temp)} ℃</h5>
</div>
`
forecastItemContainer.insertAdjacentHTML('beforeend', forecastItem);
}
function showDisplaySection (section){
[notFound, searchCity, weatherInfo].forEach(section => section.style.display = 'none');
section.style.display = 'flex';
}