Sometimes, we want to add a listener for date change in FullCalendar.
In this article, we’ll look at how to add a listener for date change in FullCalendar.
Add a Listener for Date Change in FullCalendar
To add a listener for date change in FullCalendar, we can add a dateClick
method into the object that’s passed into the FullCalendar
constructor.
For instance, we write:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/4.2.0/bootstrap/main.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/4.2.0/bootstrap/main.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/4.2.0/core/main.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/4.2.0/core/main.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/4.2.0/daygrid/main.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/4.2.0/daygrid/main.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/4.2.0/interaction/main.min.js"></script>
<div id="calendar"></div>
to add all the required script and link tags for the FullCalendar library.
We also add a div to render the calendar in.
Then we write:
document.addEventListener('DOMContentLoaded', () => {
const calendarEl = document.getElementById('calendar');
const calendar = new FullCalendar.Calendar(calendarEl, {
plugins: ["interaction", "dayGrid"],
initialView: 'dayGridMonth',
dateClick(view) {
console.log(view.date)
}
});
calendar.render();
});
to select the div with document.getElementById
.
Then we render the calendar with the FullCalendar.Calendar
constructor.
We pass in calendarEl
and an object with the dateClick
method.
The dateClick
method runs when we click on the date.
And we set the plugins
to the required plugins for rendering the calendar.
view.date
has the date we clicked on.
The interaction
and dayGrid
plugins are both loaded from the script tags.
Finally, we call calendar.render
to render the calendar.
Now when we click on a date on the calendar, we’ll see the clicked date logged.
Conclusion
To add a listener for date change in FullCalendar, we can add a dateClick
method into the object that’s passed into the FullCalendar
constructor.