Blog

Ajax Calendar with Low Events

22 November 2016 No comments

As a general rule, I try to keep my add-ons front-end agnostic. That is to say, you should be able to use any HTML, CSS or JavaScript of your choice; I will never force you to use specific markup or a JavaScript library in order to use a Low add-on.

However, sometimes, people will ask if a certain feature is included in an add-on of mine, where that feature is a front-end implementation. This could be a “live search” for Low Search or a dynamic calendar for Low Events. Both features require some JavaScript including Ajax calls and a certain setup for your ExpressionEngine templates. Here’s an example for creating the dynamic calendar.

The Calendar tag generates a monthly calendar view of events, with links to days of the month. Clicking previous or next month will open up a new page containing that month in the URI; you know, just how hyperlinks work. To enhance this progressively, we could add some JavaScript so we can navigate through the months without reloading the whole page.

To make this work, we need the following code:

  • An events/index template containing the full events page, including a <div id="cal"></div> for the calendar, like this one.
  • An events/cal template containing just the Calendar tag which we can embed in the former template, with some logic to determine the right date, like this one.
  • Some JavaScript to bring it all together.

For the JS, I used a bit of jQuery-based code, which comes down to this:

$('#cal').on('click', 'caption a', function(){
  $('#cal').load(this.href.replace('events', 'events/cal'));
  return false;
});

This basically translates to: for all (future) links in the caption-element, replace the <div id="cal"></div> content with whatever you get back from the link’s href, where we replace ‘events’ with ‘events/cal’, changing the URL from something like http://domain.com/events/2016-12 to http://domain.com/events/cal/2016-12.

This means we’re calling the embedded template directly, which is why we need the logic to determine the location of date in the URL, as seen on top of the events/cal template.

That’s it! A nice, progressively enhanced Ajax-y calendar for your clicking pleasure. Of course, you’re not obligated to use this front-end code. You can use your own combination of HTML and JavaScript. Perhaps even keep it vanilla.

Leave your comment