DEV Community

Joe Steinbring
Joe Steinbring

Posted on

How to add a JavaScript calendar to your app

I recently got it into my head that I wanted to figure out how I would write a "time-off calendar". Feature zero of any time-off calendar tends to be the calendar itself. Today, I figured that we would look at one option for that.

I combed through the assorted google results and found a promising looking solution called FullCalendar. It advertises itself as working with React, Vue, Angular, or just plain javascript. For today's post, we are going to be looking at their vanilla-javascript, 100% framework agnostic solution.

Let's start by looking at the absolutely, most basic example of a monthly calendar with the library.

You will notice that we are waiting for the DOM to load, using document.getElementById() to identify the element that is going to contain the calendar, and then we are using that new calendarEl element to render the calendar. We are defining an initialView of 'dayGridMonth' but there are the alternate options 'dayGridWeek', 'timeGridDay', or 'listWeek'.

There are a lot more options that you can apply to a calendar, beyond just initialView. For our next example, let's check out weekends and headerToolbar.

By setting weekends to false, we are getting closer to the "time-off calendar" vibe and the headerToolbar value allows us to both make the calendar look less "standard" and expose the "month", "week", and "day" toggles. The toolbar has a heck of a lot more options, too.

So, the next step is to populate the calendar with actual events. In our next example, we are directly populating an "events" object with an array of events.

When creating an event, there are a lot of options available. For this example, we are going to keep it pretty basic, though. We have two multi-day events and two single-day events. Each event has a unique ID, a title, a start, and a background color. The multi-day events also have an end. The start and end values take a date object and can include a time.

For our final example, we are going to look at how pull in the event data from a JSON endpoint. Instead of creating an actual back-end for this thing, I just spun something up using GitHub Gist. Of course, I would recommend using something like Laravel or Firebase for an actual back-end.

As you can see, adding a JSON feed instead of an object as a value for "events" is all that is needed. There are a lot more options available, though. You can even use an iCalendar feed instead of a JSON feed.

So, what's next? Next week, there will be a follow-up on how to do the same thing, using vue.js. After that, I intend to show how to incorporate Laravel into the picture. If you want to follow along, I suggest following me on here and checking out my other blog. Until then, please feel free to leave a comment if you have any questions, comments, etc.

Top comments (0)