-
Notifications
You must be signed in to change notification settings - Fork 19
/
script.js
67 lines (53 loc) · 2.48 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
// Function to fetch weather data from the API
function fetchWeatherData(city) {
const apiKey = '90cd13c6c777169fe48456c291385bd5';
const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`;
fetch(apiUrl)
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then((data) => {
// Update the UI with weather data
updateWeatherUI(data);
})
.catch((error) => {
console.error('Error fetching weather data:', error);
alert('Error fetching weather data. Please try again.');
});
}
// Function to update the UI with weather data
function updateWeatherUI(data) {
const locationElement = document.querySelector('.location h2');
const temperatureElement = document.querySelector('.temperature p');
const conditionElement = document.querySelector('.condition p');
locationElement.textContent = `${data.name}, ${data.sys.country}`;
temperatureElement.textContent = `${Math.round(data.main.temp)}°C`;
conditionElement.textContent = data.weather[0].description;
}
// Function to handle the form submission
function handleFormSubmit(event) {
event.preventDefault();
const cityInput = document.querySelector('.search input');
const cityName = cityInput.value.trim();
if (cityName) {
fetchWeatherData(cityName);
cityInput.value = ''; // Clear the input field
} else {
alert('Please enter a valid city name.');
}
}
// Attach the form submission handler to the search button
const searchButton = document.querySelector('.search button');
searchButton.addEventListener('click', handleFormSubmit);
// Function for Date and Time
function updateTime() {
const currentDateTime = new Date();
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', timeZoneName: 'short' };
const formattedDateTime = currentDateTime.toLocaleDateString('en-US', options);
document.getElementById('currentDateTime').textContent = formattedDateTime;
}
setInterval(updateTime, 1000);
updateTime();