Formatting Google Calendar event lists with jQuery techniques

After spending all day trying to solve the problem of displaying a Google calendar in list format on my website, I finally found some code that works. However, there are still some formatting issues that I can't figure out. I'm not very familiar with jQuery, so I'm struggling to fix the formatting. I've tried adjusting things on the CSS side, but it seems like some of the issues are on the script side. If someone could help me clean up the formatting in the script and make it strictly CSS-based, that would be amazing! Or if you have a better solution, please share =)

Thank you so much!

The format I'm looking for is as follows, split into three sections within different divs:

Date: 'Nov 12, 09:00' | Event: 'Student Night' | Location: 'Nicci Beach'

Javascript Code:


// Generated by CoffeeScript 1.4.0
(function() {
  // Code here...
}).call(this);

HTML Template:

<div id="gcf-custom-template">
    <div class="gcf-item-container-block">
        <div class="gcf-item-block">
            <div class="gcf-item-header-block">
                <div class="gcf-item-title-block">
                    <div style="float: left; width 250px;"><a class="gcf-item-link"><span class="gcf-item-daterange">2012-02-01 09:00</span>:</a></div>
                    <div style="float: left; width 250px;"><a class="gcf-item-location">1-877-346-9707 w 55586#</a></div>
                    <div style="float: left; width 250px;"><strong><a class="gcf-item-title">Item Title of Your event</a></strong></div>
                </div>
            </div>
        </div>
    </div>
</div>

Script Call:

<script type="text/javascript">
    var $ = jQuery;
    $(function() {
        $('#gcf-custom-template').gCalFlow({
          calid: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="053171356834662b72353263456268646c692b666a68">[email protected]</a>',
          maxitem: 50,
          mode: 'updates',
          date_formatter: function(d, allday_p) { return (d.getMonth()+1) + "/" + d.getDate() + "/" + d.getYear().toString().substr(-2) }
        });
      });
</script>

Answer №1

In solving a similar issue, I utilized moment.js for date formatting, markupjs for templating, and jQuery to simplify tasks.

// Custom pipe in markup.js using moment.js for formatting
Mark.pipes.moment = function (date, format) {
    return moment(new Date(date)).format(format);
};

// Another custom pipe in markup.js to compare if two dates are in the same month
Mark.pipes.diffmonth = function (date1, date2) {
  moment1 = moment(new Date(date1));
  moment2 = moment(new Date(date2));
  var ret= moment1.month()!=moment2.month();
  return ret;
};

// A filter pipe in markup.js for arrays
Mark.pipes.sift = function (arr, prop, val) {
  return $.grep(arr,function(item) {
    return item[prop] == val;
  });
};

$(document).ready(loadCalendarData);

// Fetching data from Google Calendar public JSON feed 
calendarURL = "http://www.google.com/calendar/feeds/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="093f7f7f3e7d6a7d31396e7f3c7d6b656861643c7a6e397f7a667a496e7b667c79276a68656c676d687b276e66666e656c276a6664">[email protected]</a>/public/full?alt=json-in-script&orderby=starttime&singleevents=true&sortorder=ascending&futureevents=true&callback=?";

function loadCalendarData() {
  $.getJSON( calendarURL, applyTemplate);
}

function applyTemplate(cal_data) {

  // Setting language to French for date formatting
  moment.lang("fr");

  // Extracting VCALENDAR fields from Google Calendar JSON feed and adding a type field for event distinction
  var events = $.map(cal_data["feed"]["entry"], function (event) {
    var url= $.grep(event["link"], function(link) {
      return link["rel"]=="related";
    });
    return {
      "summary": event["title"]["$t"],
      "dtstart": event["gd$when"][0]["startTime"],
      "dtend": event["gd$when"][0]["endTime"],
      "url": url[0]?url[0]["href"]:"",
      "location": event["gd$where"][0]["valueString"],
      "type": (moment.duration(new Date(event["gd$when"][0]["endTime"])-new Date(event["gd$when"][0]["startTime"])).as("hours")<18)?"single":"multi"
    };

  });

  // Adding template features for dynamic content display
  Mark.includes.linked_summary = "{{if url}}<a href='{{url}}'>{{/if}}{{summary}}{{if url}}</a>{{/if}}";
  Mark.includes.optional_location = "{{if location}}&nbsp;({{location}}){{/if}}"

  // Generating separate lists for different types of events based on start dates
  var template = 
    "Upcoming Events:<ul>{{events|sift>type>single}}"+ 
    "<li>{{dtstart|moment>dddd|capcase}} {{dtstart|moment>D/M}}: {{linked_summary}}{{optional_location}}</li>"+
    "{{/events}}</ul>"+
    "<br>"+
    "Multi-day Events Coming Up (2013/2014):<ul>{{events|sift>type>multi}}"+
    "<li>{{dtstart|moment>D}}{{if dtstart|diffmonth>`dtend`}}{{dtstart|moment>/M}}{{/if}}-{{dtend|moment>D/M}}: {{linked_summary}}{{optional_location}}</li>"+
    "{{/events}}</ul>";

  $("#web").html(Mark.up(template, {"events":events}));
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you provide instructions on creating a marker like this in an unordered list?

Is there a way to create a bold line like this within a bulleted list easily? https://i.sstatic.net/pw8Zt.png I've tried using the border property, but it's not showing up correctly. Any quick and simple solutions for achieving this effect? Th ...

Jquery click event only firing once

My challenge is drawing lines between two points, although I've managed to do it once. The issue arises when I try to repeat the process; nothing happens on the second click of a circle. Please note that this functionality only works in modern brow ...

The bootstrap modal display issue: black background visible

In my HTML file, there are two modal dialogs that seem to be causing an issue. Interestingly, whichever modal dialog is placed first in the sequence of the HTML code displays properly when the button is clicked (and vice versa). Both modal dialogs have u ...

Using JavaScript with React to invoke an asynchronous action within a component

Within my class, I have implemented some asynchronous actions in the ComponentDidMount method. The code snippet looks like this: componentDidMount(){ // var my_call = new APICall() Promise.resolve(new APICall()).then(console.log(FB)) } class API ...

Vue3 TypeScript may potentially have an object that is 'undefined'

This piece of code is Vue3 with TypeScript-based. export interface TenantDto { uuid: string; name: string; } export const useTenantStore = defineStore('tenant', { state: () => ({ tenants: [], }), actions: { setMyTenants: (pa ...

Can you explain the meaning of "|| [];"?

Can you explain the significance of || [] in this code snippet and provide some insight into why it's included? getPair: function() { return this.props.pair || []; }, ...

Show a SweetAlert message if a specific Div Class is not found within the page

Seeking assistance with displaying a SweetAlert popup only if a certain div class is not found on the page. It appears to work when using an ID, but not with classes. Any suggestions on how to trigger this popup if the specified div class is absent? < ...

Preserve the parameter navigation stored within a flatlist and showcase it on a separate screen

I am looking to save a navigation parameter from a flatlist so that it can be displayed on another screen. This parameter is essentially a title stored in an array for the flatlist. react-native ScreenA <FlatList data={ this.state.FlatListItems } key ...

Looking for a JavaScript function that can utilize AJAX to execute PHP code and display the PHP output on the webpage

I've been trying to use JavaScript to execute some PHP code and then display the results on the page. I came across a piece of code that achieves this using ajax and by placing the PHP code in an external file. However, the code I found seems to show ...

Establishing standard emit actions in a Vue JS component layout

I am dealing with a complex situation involving two nested Vue JS components. The child component is emitting certain events to the parent function, which I have defined within the parent component declaration. The issue here is that these events are being ...

Expect for a variety of Observables to finish at different times

I am faced with the challenge of extracting data from an API that is paginated, and unfortunately, I cannot determine the total number of pages in advance. However, I can identify when I have reached the last page. My goal is to develop a function that ret ...

JQuery parsing JSON syntax

I'm working on a page that requires a quick login check and then accesses a web service to retrieve some JSON data. The response data I am getting looks like this: { 'RESPONSE' : 'INVALID','CAMPAIGNID' : '0',&a ...

Cannot get the "middle" div in CSS to properly wrap around its content

Click here to view the issue with the "middle" div not wrapping its content. I have been attempting to make it automatically wrap the entire content of the table, resulting in a neat white 10 pixel padded border surrounding it. Despite trying various metho ...

The subscription for the second Observable in RxJS concatMap is triggered individually

I am currently developing an Angular 6 application. I want the app to display a loading animation whenever there is a change in the route or if there are any pending HTTP requests. To achieve this, I have set up two Observables as follows: For httpPendingR ...

In Laravel, Inertia.js will automatically close a modal if there are no validation errors present

Here is the method I am currently using: methods: { submit() { this.$inertia.post('/projects', this.form); this.openModal = false; }, }, Unfortunately, this method closes the modal even if there are validation erro ...

Struggling to integrate a Bootstrap theme into your Ruby on Rails application?

Having trouble importing a bootstrap theme into my rails application. https://github.com/puikinsh/sufee-admin-dashboard I've been struggling to import this template for two days now with no success. It should be simple, but I can't figure out w ...

content organized in tabs using the fancybox feature

I am attempting to dynamically load content using AJAX with fancybox. It loads fine, but the tab won't change if I use the default function or via AJAX. However, if I use fancybox and set the type to 'iframe,' it loads and alternates tabs p ...

The result after calling JSON.parse(...) was not accurate

The following method is used in the controller: @RequestMapping(value = "channelIntentionDetails.html", method = RequestMethod.POST) public @ResponseBody Report getChannelIntentionDetails(@RequestBody SearchParameters searchParameters) { LOGGER.in ...

Preventing Double Click Events on jQuery Spinner

I have been working on an option picker, but now there is a new requirement to make the options configurable. While this shouldn't be too difficult, I am facing some issues with the option picker: Currently, when an item is double-clicked, it will ge ...

JSON parsing failed due to the occurrence of an unexpected token "<" at the beginning of the file

I seem to be encountering an issue with retrieving data using ajax. When I test locally, it returns the desired output. However, upon publishing the project on the server with IIS, it shows a HTML Code of my page along with an error message "syntax Error: ...