-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
99 lines (79 loc) · 2.64 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Select elements
let currentMonth = document.querySelector('#current-date h1');
let currentDayAndYear = document.querySelector('#current-date p');
let backButton = document.getElementById('back-btn');
let nextButton = document.getElementById('next-btn');
let monthDays = document.getElementById('days');
// Current date object
let date = new Date();
// Set current day and year
currentDayAndYear.textContent = date.toLocaleDateString(
"en-US",
{ weekday: 'long', day: 'numeric', year: 'numeric' }
);
// Function to render state of calendar
let renderCalendar = () => {
// Set current month
let months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
// Set current month
currentMonth.textContent = months[date.getMonth()];
// Get Total days of current month
let totalDaysInCurrentMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
// Get Total days of last month
let totalDaysInLastMonth = new Date(date.getFullYear(), date.getMonth(), 0).getDate();
// Get total days of last month to show in calendar
let totalOfLastDays = (totalDaysInLastMonth - date.getDay())
// set days of last month
let days = "";
for (let x = totalDaysInLastMonth; x > totalOfLastDays; x--)
{
days += `<div class="prev-date">${x}</div>`;
}
// Set days of current month
for (let y = 1; y <= totalDaysInCurrentMonth; y++)
{
if(y == date.getDate() && date.getMonth() === new Date().getMonth())
{
days += `<div class="today">${y}</div>`
}
else {
if (y == date.getDate() && date.getMonth() === new Date().getMonth())
{
continue;
}
days += `<div>${y}</div>`;
}
}
// Calculate total of next days to show
let totalofNextDays = 42 - ((totalDaysInLastMonth - totalOfLastDays) + totalDaysInCurrentMonth);
// Set days of next month
for (let z = 1; z <= totalofNextDays; z++)
{
days += `<div class="next-date">${z}</div>`;
monthDays.innerHTML = days;
}
}
renderCalendar();
// Add event to next month button
nextButton.addEventListener('click', () => {
date.setMonth(date.getMonth() + 1);
renderCalendar();
})
// Add event to last month button
backButton.addEventListener('click', () => {
date.setMonth(date.getMonth() - 1);
renderCalendar();
})