Sure, here is a simple example of an event calendar using JavaScript:
HTML:
```html
<div id="calendar"></div>
```
CSS:
```css
#calendar {
display: grid;
grid-template-columns: repeat(7, 1fr);
grid-template-rows: repeat(6, 1fr);
gap: 10px;
height: 500px;
width: 500px;
}
.day {
display: flex;
flex-direction: column;
align-items: flex-end;
justify-content: flex-start;
height: 100%;
width: 100%;
padding: 5px;
border: 1px solid black;
}
.day:hover {
background-color: lightgray;
}
.day .number {
font-size: 24px;
font-weight: bold;
}
.day .event {
font-size: 14px;
margin-top: 5px;
}
```
JavaScript
```javascript
const calendar = document.getElementById("calendar");
const months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
const daysOfWeek = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const currentDate = new Date();
let currentMonth = currentDate.getMonth();
let currentYear = currentDate.getFullYear();
function generateCalendar(month, year) {
const firstDay = new Date(year, month, 1);
const lastDay = new Date(year, month + 1, 0);
const daysInMonth = lastDay.getDate();
const startingDay = firstDay.getDay();
calendar.innerHTML = "";
const monthYearHeader = document.createElement("div");
monthYearHeader.innerText = `${months[month]} ${year}`;
monthYearHeader.style.gridColumn = "1 / -1";
calendar.appendChild(monthYearHeader);
for (let i = 0; i < daysOfWeek.length; i++) {
const dayOfWeekHeader = document.createElement("div");
dayOfWeekHeader.innerText = daysOfWeek[i];
dayOfWeekHeader.classList.add("day");
dayOfWeekHeader.style.fontWeight = "bold";
dayOfWeekHeader.style.backgroundColor = "lightgray";
calendar.appendChild(dayOfWeekHeader);
}
let date = 1;
for (let i = 0; i < 6; i++) {
for (let j = 0; j < 7; j++) {
if (i === 0 && j < startingDay) {
const emptyDay = document.createElement("div");
emptyDay.classList.add("day");
calendar.appendChild(emptyDay);
} else if (date > daysInMonth) {
break;
} else {
const day = document.createElement("div");
day.classList.add("day");
day.innerHTML = `<div class="number">${date}</div>`;
// Add events to the day
const events = [
{ time: "10:00 AM", title: "Meeting with John" },
{ time: "2:00 PM", title: "Dentist appointment" },
{ time: "7:00 PM", title: "Dinner with friends" },
];
for (let k = 0; k < events.length; k++) {
if (date === events[k].date && month === events[k].month && year === events[k].year) {
const event = document.createElement("div");
event.classList.add("event");
event.innerText = `${events[k].time}: ${events[k].title}`;
day.appendChild(event);
}
}
calendar.appendChild(day);
date++;
}
}
}
}
generateCalendar(currentMonth, currentYear);
```
This code generates a calendar for the current month and year, and displays events for each day based on the `events` array. Note that the `events` array is currently hard-coded, but you can modify it to dynamically retrieve events from a database or API.
No comments:
Post a Comment