-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
69 lines (67 loc) · 2.71 KB
/
Copy pathindex.js
File metadata and controls
69 lines (67 loc) · 2.71 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
const modeIcon = document.querySelector('#mode-icon');
const body = document.body
modeIcon.addEventListener('click', () => {
let isLight = body.getAttribute('data-theme') === 'light';
// synchronisation de l'icône
body.setAttribute('data-theme', isLight ? 'dark' : 'light');
modeIcon.src = isLight ? 'assets/night-mode.png' : 'assets/light-mode.png';
})
/* ---------------------- WEATHER API ----------------------*/
const apiKey = "7080968bb88418c2bd9844a874faffd6"
const input = document.querySelector('#input');
const searchBtn = document.querySelector('#search-btn');
/* ---------------------- FETCH INFOS ----------------------*/
const city = document.querySelector('#city');
const date = document.querySelector('#date');
const weatherImg = document.querySelector('#weather');
const temp = document.querySelector('#temp');
const description = document.querySelector('#description');
const wind = document.querySelector('#wind');
function fetchWeather(cityName) {
const url = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&units=metric&appid=${apiKey}`
fetch(url)
.then(res => {
if (!res) throw new Error('No results found');
return res.json();
})
.then(data => {
console.log(data);
city.textContent = data.name;
temp.textContent = `${data.main.temp} °C`
description.textContent = data.weather[0].description;
wind.textContent = `vitesse de vent : ${data.wind.speed} km/h`;
const now = new Date()
date.textContent = now.toLocaleDateString('fr-FR')
changeWeatherImage(description.textContent)
})
.catch(error => console.log(error));
}
function handleSearch() {
if (input.value.trim() !== '')
fetchWeather(input.value);
}
/* ---------------------- EVENT LISTENER ----------------------*/
searchBtn.addEventListener('click', handleSearch);
input.addEventListener('keydown', (e) => {
if (e.key === "Enter") handleSearch();
})
/* ---------------------- DEFAULT ----------------------*/
fetchWeather("Antibes");
/* ---------------------- ICON UPDATE ----------------------*/
function changeWeatherImage(desc) {
if (desc.includes("rain")) {
weatherImg. src = "assets/rainy.png";
}
else if (desc.includes("scattered") || desc.includes("broken")) {
weatherImg. src = "assets/scattered.png";
}
else if (desc.includes("sun") || desc.includes("clear")) {
weatherImg. src = "assets/sunny.png";
}
else if (desc.includes("overcast") || desc.includes("clouds")) {
weatherImg. src = "assets/overcast.png";
}
else if (desc.includes("mist")) {
weatherImg. src = "assets/cloud.png";
}
}