I have been experimenting with new HTML tags. Below are a result of few.
Experiment # 1
Card to Display Time and Weather
Code for the above card
<style>
.card {
background-color: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
text-align: center;
width: 300px;
}
</style>
<div class="card">
<div class="clock" id="clock"></div>
<div class="date" id="date"></div>
<div class="weather" id="weather">
<div id="weather-text"></div>
<img id="weather-icon" src="" alt="Weather Icon" />
</div>
</div>
<script>
const API_KEY = 'Use your Own API Keys';
const CITY = 'Bengaluru';
function updateClock() {
const clock = document.getElementById('clock');
const dateElement = document.getElementById('date');
const now = new Date();
let hours = now.getHours();
const minutes = now.getMinutes().toString().padStart(2, '0');
const seconds = now.getSeconds().toString().padStart(2, '0');
const ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
const hoursStr = hours.toString().padStart(2, '0');
clock.textContent = `${hoursStr}:${minutes}:${seconds} ${ampm}`;
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const day = days[now.getDay()];
const date = now.getDate();
const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const month = monthNames[now.getMonth()];
const year = now.getFullYear();
const ordinalSuffix = (n) => {
const s = ["th", "st", "nd", "rd"];
const v = n % 100;
return n + (s[(v - 20) % 10] || s[v] || s[0]);
}
const formattedDate = `${ordinalSuffix(date)} ${month} ${year}`;
dateElement.textContent = `${day}, ${formattedDate}`;
}
async function fetchWeather() {
const weatherText = document.getElementById('weather-text');
const weatherIcon = document.getElementById('weather-icon');
try {
const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${CITY}&appid=${API_KEY}&units=metric`);
const data = await response.json();
const temperature = data.main.temp;
const description = data.weather[0].description;
const icon = data.weather[0].icon;
weatherText.textContent = `${CITY}: ${temperature}°C, ${description}`;
weatherIcon.src = `http://openweathermap.org/img/wn/${icon}@2x.png`;
weatherIcon.alt = description;
} catch (error) {
weatherText.textContent = 'Unable to fetch weather data';
weatherIcon.src = '';
weatherIcon.alt = '';
}
}
setInterval(updateClock, 1000);
updateClock(); // Initial call to display clock immediately
fetchWeather(); // Initial call to fetch weather immediately
setInterval(fetchWeather, 600000); // Update weather every 10 minutes
</script>
Leave a Reply