-
Notifications
You must be signed in to change notification settings - Fork 576
/
Copy pathscript.js
174 lines (137 loc) · 7.68 KB
/
script.js
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
/* JSON file - Weather API */
const API_KEY = "3cc790b1653416aade4ba256c95e0c67"
const BASE_URL = "https://api.openweathermap.org/data/2.5/weather"
const FORECAST_BASE_URL = "https://api.openweathermap.org/data/2.5/forecast?"
let cityWeather = "Sevilla";
/* URL for API */
const URL = `${BASE_URL}?q=${cityWeather}&units=metric&APPID=${API_KEY}`
const FORECAST_URL = `${FORECAST_BASE_URL}q=${cityWeather}&units=metric&APPID=${API_KEY}`
/* Function to fetch weather data based on the city name */
/* Get references to the input field and button */
// const searchInput = document.getElementById("city-input");
// const searchButton = document.getElementById("btn-city-input");
// /* Add event listener for the button click */
// searchButton.addEventListener("click", function() {
// cityWeather = searchInput.value;
// console.log('Search query:', cityWeather);
// });
// // Trigger the search when the Enter key is pressed
// searchInput.addEventListener('keypress', function(event) {
// if (event.key === 'Enter') {
// // Prevent the default action of the Enter key (form submission, etc.)
// event.preventDefault();
// // Get the value from the search input field
// cityWeather = searchInput.value;
// // Log the search query
// console.log('Search query (Enter pressed):', cityWeather);
// }
// });
/* DOM selectors */
const weatherTitle = document.getElementById("title-weather")
const weatherIcon = document.getElementById("icon-weather")
const weatherType = document.getElementById("upper-info-weather-type")
const weatherTemp = document.getElementById("upper-info-weather-temp")
const timeSunrise = document.getElementById("upper-info-sunrise-time")
const timeSunset = document.getElementById("upper-info-sunset-time")
const forecastWrapper = document.getElementById('ForecastWrapper')
/* Sparad data från JSON-fil */
const showNewHTML = (data) => {
/* const cityName = data.name;
cityWeather.innerText = cityName */
const description = data.weather[0].description
weatherType.innerText = description
const temp = data.main.temp
const roundedTemp = temp.toFixed(1);
weatherTemp.innerText = roundedTemp
/* Sunrise and sunset */
const sunrise = data.sys.sunrise;
const sunset = data.sys.sunset;
// Convert UNIX time to a readable format
const sunriseDate = new Date(sunrise * 1000);
const sunsetDate = new Date(sunset * 1000);
// Format the time (HH:MM)
const sunriseFormatted = sunriseDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
const sunsetFormatted = sunsetDate.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
timeSunrise.innerText = sunriseFormatted
timeSunset.innerText = sunsetFormatted
/* Layout to what weather is shown */
if (description.includes("clear")) {
document.body.classList.remove("weather-card-clear", "weather-card-rain", "weather-card-cloudy", "btn-city-input-cloudy", "city-input-cloudy", "btn-city-input-rain", "city-input-rain"); // Rensa tidigare klasser
weatherTitle.innerText = `Get your sunnies on. ${cityWeather} is looking rather great today.`;
weatherIcon.src = "../assets/design-2/noun_Sunglasses_2055147.svg"; // Bild för soligt väder
document.body.classList.add("weather-card-clear");
document.getElementById("city-input").className = "city-input-clear";
document.getElementById("btn-city-input").className = "btn-city-input-clear";
} else if (description.includes("rain")) {
document.body.classList.remove("weather-card-clear", "weather-card-rain", "weather-card-cloudy", "btn-city-input-cloudy", "city-input-cloudy", "btn-city-input-clear", "city-input-clear", "btn-city-input-rain", "city-input-rain"); // Rensa tidigare klasser
weatherTitle.innerText = `Don’t forget your umbrella. It’s wet in ${cityWeather} today.`;
weatherIcon.src = "../assets/design-2/noun_Umbrella_2030530.svg"; // Bild för regnigt väder
document.body.classList.add("weather-card-rain");
document.getElementById("city-input").className = "city-input-rain";
document.getElementById("btn-city-input").className = "btn-city-input-rain";
} else if (description.includes("cloud")) {
document.body.classList.remove("weather-card-clear", "weather-card-rain", "weather-card-cloudy", "btn-city-input-cloudy", "city-input-cloudy", "btn-city-input-clear", "city-input-clear", "btn-city-input-rain", "city-input-rain"); // Rensa tidigare klasser
weatherTitle.innerText = `Light a fire and get cosy. ${cityWeather} is looking grey today. `;
weatherIcon.src = "../assets/design-2/noun_Cloud_1188486.svg"; // Bild för molnigt väder
document.body.classList.add("weather-card-cloudy");
document.getElementById("city-input").className = "city-input-cloudy";
document.getElementById("btn-city-input").className = "btn-city-input-cloudy";
} else {
document.body.classList.remove("weather-card-clear", "weather-card-rain", "weather-card-cloudy", "btn-city-input-cloudy", "city-input-cloudy", "btn-city-input-clear", "city-input-clear", "btn-city-input-rain", "city-input-rain"); // Rensa tidigare klasser
weatherTitle.innerText = `${cityWeather} is offering a weather today thats not in my vocabulary.`;
weatherIcon.src = "../assets/design-2/noun_Cloud_1188486.svg"; // Bild för molnigt väder
document.body.classList.add("weather-card-cloudy");
document.getElementById("city-input").className = "city-input-cloudy";
document.getElementById("btn-city-input").className = "btn-city-input-cloudy";
}
}
/* Hämta data/väderlek från JSON-fil */
fetch(URL)
.then(response => response.json())
.then(data => {
console.log(data)
showNewHTML(data)
})
/* Hämta data/väderlek för 5 dagar från JSON-fil */
fetch(FORECAST_URL)
.then(response => response.json())
.then(data => {
updateForecastHTML(data)
})
const updateForecastHTML = (data) => {
forecastWrapper.innerHTML = '' // Clear previous forecast
const forecastArray = data.list
// Group forecasts by day
const dailyForecasts = {}
forecastArray.forEach(entry => {
const date = new Date(entry.dt * 1000)
const day = date.toLocaleDateString('en-SE', { weekday: 'short' })
const today = new Date().toLocaleDateString('en-SE', { weekday: 'short' })
if (day === today) return // Skip today's forecast
if (!dailyForecasts[day]) {
dailyForecasts[day] = []
}
dailyForecasts[day].push(entry)
})
// Process each day's forecast
Object.keys(dailyForecasts).forEach(day => {
const forecasts = dailyForecasts[day]
let tempHigh = -Infinity
let tempLow = Infinity
forecasts.forEach(forecast => {
if (forecast.main.temp_max > tempHigh) {
tempHigh = forecast.main.temp_max
}
if (forecast.main.temp_min < tempLow) {
tempLow = forecast.main.temp_min
}
})
const forecastRow = document.createElement('div')
forecastRow.classList.add('forecast-row')
forecastRow.innerHTML = `
<div class="forecast-day">${day}</div>
<div class="forecast-temp">${Math.round(tempHigh)} / ${Math.round(tempLow)}°C</div>
`
forecastWrapper.appendChild(forecastRow)
})
}