Sunday, February 16, 2014

TimelineJS configured dynamically with a string

TimelineJS is probably the prettiest and most reliable timeline software that works over the Web. Unfortunately there are some limitations: first that it only handles about 100 entries, although we regularly use much more than that and its performance is OK. The big problem is getting it to read from a string returned by a server. The documentation is unclear on this, so here is an attempt to spell out the technique with an example (lacking in the software distribution).

TimelineJS is configured via a JSON config object. Once timeline_config is set to this structure and TimelineJS is loaded, the config is read and the timeline gets set up automatically. To invoke it dynamically you have to specify a javascript object as input instead of a file name for the source config property. To create this JS object I put the following in a <script> element in the <head> of my HTML. For this to work you must previously have loaded both the jQuery and "../build/js/storyjs-embed.js" scripts:

function httpGet(theUrl) {
    var xmlHttp = null;
    xmlHttp = new XMLHttpRequest(); "GET", theUrl, false );
    if ( xmlHttp.readyState==1 )
        xmlHttp.send( null );
    return xmlHttp.responseText;
$(document).ready(function() {
var dataObject = httpGet("http://localhost/json/timeline/");
if ( dataObject != null )
    var jsObject = eval("("+dataObject+")");
       type:       'timeline',
       width:      '100%',
       height:     '100%',
       source:     jsObject,
       embed_id:   'my-timeline'

This does a http GET via an AJAX call to get the JSON, objectify it using eval, and then call createStoryJS, passing in the JSON config object. The JSON just follows the format given in the documentation. In our case we didn't want the "asset" property so we just left it out. It seems to work OK. This way you can create the timeline after the page has loaded. All it needs is a <div id="my-timeline"> in the body of the HTML for it to work.

No comments:

Post a Comment