JSFiddle - React, Tailwind, and code Playground
by Dhanck
HTML
<h1>Holiday Calendar</h1>
<label for="countrySelect">Select Countries:</label>
<select id="countrySelect" multiple>
<option value="US">United States</option>
<option value="GB">United Kingdom</option>
<option value="ES">Spain</option>
<option value="FR">France</option>
<option value="JP">Japan</option>
<option value="SG">Singapore</option>
<option value="CN">China</option>
</select>
<label for="yearInput">Enter Year:</label>
<input type="number" id="yearInput" min="1900" max="4500" placeholder="Current year">
<div id="calendar"></div>
CSS
body {
font-family: Arial, sans-serif;
}
h1 {
text-align: center;
}
label {
margin-right: 10px;
}
select {
padding: 5px;
font-size: 16px;
min-height: 100px;
width: 200px;
overflow-y: scroll;
}
#calendar {
margin-top: 20px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
ul {
list-style: none;
padding: 0;
}
li {
margin-bottom: 5px;
}
JavaScript
async function fetchHolidays(countryCodes) {
try {
const currentYear = new Date().getFullYear();
const yearInput = document.getElementById('yearInput');
let year = currentYear;
if (yearInput && yearInput.value) {
year = parseInt(yearInput.value);
}
const requests = countryCodes.map(code =>
fetch(`https://date.nager.at/api/v3/publicholidays/${year}/${code}`)
);
const responses = await Promise.all(requests);
const holidayLists = await Promise.all(responses.map(async res => {
if (!res.ok) {
throw new Error('Failed to fetch holidays for one or more countries.');
}
return await res.json();
}));
return holidayLists.flat();
} catch (error) {
console.error(error.message);
return null;
}
}
function displayHolidays(holidays) {
const calendarDiv = document.getElementById('calendar');
calendarDiv.innerHTML = '';
if (!holidays || holidays.length === 0) {
calendarDiv.innerHTML = '<p>No holidays found for selected countries.</p>';
return;
}
const ul = document.createElement('ol');
holidays.forEach(holiday => {
const li = document.createElement('li');
li.textContent = `${holiday.date}: ${holiday.name}`;
ul.appendChild(li);
});
calendarDiv.appendChild(ul);
}
document.getElementById('countrySelect').addEventListener('change', async function() {
const selectedCountries = Array.from(this.selectedOptions).map(option => option.value);
const holidays = await fetchHolidays(selectedCountries);
displayHolidays(holidays);
});
document.addEventListener('DOMContentLoaded', async () => {
const defaultCountries = ['US']; // Default countries selected
const holidays = await fetchHolidays(defaultCountries);
displayHolidays(holidays);
});