Skip to content

Instantly share code, notes, and snippets.

@leoherzog
Last active April 9, 2017 00:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leoherzog/2e5327db9d4c63b14bc079bf7756bdc8 to your computer and use it in GitHub Desktop.
Save leoherzog/2e5327db9d4c63b14bc079bf7756bdc8 to your computer and use it in GitHub Desktop.
A quick-'n-dirty jQuery way of changing an HTML div contents based on if you are currently free or busy in Google Calendar
  • Make sure you are sharing at least free/busy details about your calendar to the public
  • Add freebusy.js and jQuery (with ajax support, not jQuery slim) to your project
  • Make an API Key at the Google Developers Console and enable Google Calendar support
  • Change the API key at line 5
  • Change the Google Calendar address from googlecalendarid@gmail.com to the one that you want to check on line 6
  • ???
  • Profit
window.onload = getFreeBusy();
setInterval(getFreeBusy, 15000); // update the div every 15 seconds
function getFreeBusy() {
var gcalapikey = 'yourgcalapikey';
var calendarid = 'googlecalendarid@gmail.com';
var currentDateTime = new Date();
var formattedDateTime = currentDateTime.toISOString(); // formattedDateTime is the current date time in Google Calendar-acceptable format
var currentDateTimePlusTenSeconds = new Date();
currentDateTimePlusTenSeconds.setSeconds(currentDateTimePlusTenSeconds.getSeconds() + 10 );
var formattedDateTimePlusTenSeconds = currentDateTimePlusTenSeconds.toISOString(); // same thing for formattedDateTimePlusTenSeconds, but... plus ten seconds. gasp.
var postVariablesArray = new Array(); // let's construct the stuff that we need to POST to the Google Calendar API
postVariablesArray[0] = "{'items': [{'id': '" + calendarid + "'}]";
postVariablesArray[1] = "'timeMin': '" + formattedDateTime + "'";
postVariablesArray[2] = "'timeMax': '" + formattedDateTimePlusTenSeconds + "'}";
var postVariables = postVariablesArray.join(',');
$.ajax({
url: 'https://www.googleapis.com/calendar/v3/freeBusy?key=' + gcalapikey,
type: 'POST',
data: postVariables, // variables from above
contentType: 'application/json; charset=utf-8',
dataType: 'json'
})
.done (function(data){
if (data["calendars"][calendarid]["busy"].length === 0) { // no events going on right now
$("#freeorbusylabel").html('✓ I am Currently Free!');
}
else { // must be some event(s) going on right now
$("#freeorbusylabel").html('✗ I am Currently Busy');
}
});
};
<html>
<body>
<div id="freeorbusylabel">Checking...</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment