-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
61 lines (46 loc) · 2.08 KB
/
Copy pathmain.js
File metadata and controls
61 lines (46 loc) · 2.08 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
const apiKey = '6060xxx';
// Elemente auf der Seite
const header = document.querySelector("#header");
const form = document.querySelector("#form");
const input = document.querySelector("#inputCity");
/* Hören auf das Absenden des Formulars */
form.onsubmit = function(e) {
e.preventDefault();
// Den Wert aus dem Input-Feld nehmen und Leerzeichen entfernen
let city = input.value.trim();
if (city === '') return; // Keine leere Anfrage senden
// URL für die Anfrage
const url = `http://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${city}`;
// Anfrage ausführen
fetch(url)
.then(response => response.json())
.then(data => {
console.log(data);
// Entfernen der vorherigen Karte, falls vorhanden
const prevCard = document.querySelector('.card');
if (prevCard) prevCard.remove();
// Fehlerprüfung
if (data.error) {
const html = `<div class="card">${data.error.message}</div>`;
header.insertAdjacentHTML('afterend', html);
} else {
// Markup für die Wetterkarte
const iconUrl = `https:${data.current.condition.icon}`;
const html = `<div class="card">
<h2 class="card-city">${data.location.name}<span> ${data.location.country}</span></h2>
<div class="card-weather">
<div class="card-value">${data.current.temp_c}<sup>°C</sup></div>
<img class="card-img" src="${iconUrl}" alt="${data.current.condition.text}">
</div>
<div class="card-description">${data.current.condition.text}</div>
</div>`;
// Karte anzeigen
header.insertAdjacentHTML('afterend', html);
}
})
.catch(() => {
// Fehlerbehandlung bei der Netzwerkverbindung
const html = `<div class="card">Fehler bei der Verbindung mit der API</div>`;
header.insertAdjacentHTML('afterend', html);
});
};