jQuery.silver_track

A smart and very extensible jquery sliding carousel

Download .zip Download .tar.gz View on GitHub

Remote Content

This plugin provides a way to load content through ajax. Example in the end of the page.

Options

name description default
lazy It determines if RemoteContent will fetch the first page after the track starts or just when the user navigate to a page without cache. You will usually set this to false when you render your first page with the track and get the other items through ajax true
prefetchPages The amount of pages that will be prefetched ahead of time. It is based on current page so if you have configured "prefetchPages: 2" it will start loading 3 pages (the first + 2) and will keep the distance of 2 pages until the end, so when the current page is 2 there will be 4 loaded pages and so on 0
type The type of request to make ("POST" or "GET"). This parameter is sent direct to ajaxFunction GET
params Data to be sent to the server. This parameter is sent to option "data" of ajaxFunction {}
url A string containing the URL to which the request is sent or a function that returns an url. If this option is a function, it will receive a reference of track, the page number and the perPage value, if not RemoteContent will try to replace the substrings {page} and {perPage} with the current values
ajaxFunction A custom function for ajax. It defaults to $.ajax, if defined the provided function will receive the same options of $.ajax. It allows other ajax implementations such as ajaxQ or something based on promises $.ajax

Callbacks

* Take a look at the opts values after the table of callbacks

name description arguments
beforeStart Called before the track starts track
beforeSend It is a pre-request callback, it could be used to include spinners/loaders and do whatever you want before the request track, jqXHR, settings, opts
beforeAppend Called before the content generated by the processor is attached to the DOM track, items, opts
afterAppend Called after items are attached to the DOM and their positions were updated track, items, opts
process It is a function that will process the data loaded by the server and return an array of DOM items that will be appended to the DOM track, perPage, data, opts
updateTotalPages It will be called after the afterAppend callback to update the total pages of the track based on the data loaded by the server track, data
onError Called whenever an error happens with the request track, jqXHR, textStatus, errorThrown, opts

* Possible opts values:

{prefetch: false}
// or
{prefetch: true, currentPage: 1}

Methods

name description parameters
reload Reload the content of track. This method flushes the cache and removes the items. If the track is lazy the first page is fetched after the reload

Example

For our example, we will use a server called "echo" that responds with the same JSON that we set through the parameter json, it will also return the total pages number that we set with the parameter total_pages.

Because we are lazy people we will use the lazy option true, that is already set by default, thus the markup will be like:

<div class="track">
  <div class="view-port">
    <div class="slider-container">
      <!-- no items, lazy developers! -->
    </div>
  </div>

  <div class="pagination">
    <a href="#" class="prev disabled"></a>
    <a href="#" class="next disabled"></a>
  </div>
</div>

For this examples we will need some support functions. We need to generate a fake json to allow the echo server to return json and we will also need to generate the appropriate url with the json parameter set. This is just necessary to the example, in your code you will point to your service url and won't need any fake json generator.

// Let's create a function to create the urls for our "echo" test server
var urlToEchoServer = function(track, page, perPage) {
  var jsonText = escape(JSON.stringify(fakeJsonCreator(page, perPage)));
  var echoServerHost = "http://echo-server.herokuapp.com";
  return echoServerHost + "/echo/json/" + page + "?json=" + jsonText + "&total_pages=5";
}

// Support function for our test
var fakeJsonCreator = function(page, perPage) {
  var photoTypes = ["food", "people", "nature", "sports"];
  var items = [];
  for (var i = 0; i < perPage; i++) {
    items.push({img_url: "http://lorempixel.com/224/128/" + photoTypes[i]});
  }

  return items;
}

Then we will create our processor, the function that will transform the data from the server into an array of DOM elements, and install our plugin

// Let's create our processor, the function that will transform the data
// from the server into an array of DOM elements
var processor = function(track, perPage, json) {
  var array = [];

  for (var i = 0; i < perPage; i++) {
    if (json.data[i] === undefined) {
      break;
    }

    array.push(
      $("<div></div>", {"class": "item"}).append($("<img>", {"src": json.data[i].img_url}))
    );
  }

  return array;
}

// Then we install the plugin
track.install(new SilverTrack.Plugins.RemoteContent({
  url: urlToEchoServer,
  process: processor,

  beforeStart: function(track) {
    track.container.parent().append($("<div></div>", {"class": "loading"}));
  },

  beforeSend: function(track) {
    $(".loading", track.container.parent()).fadeIn();
  },

  beforeAppend: function(track, items) {
    $(".loading", track.container.parent()).hide();
  },

  updateTotalPages: function(track, json) {
    track.updateTotalPages(json.total_pages);
  }
}));

and it's done!

Reloading with another content

The RemoteContent plugin has a method to reload the content of the track flushing all the cache, with this method we can load another content to the track just changing the URL before call it. We will use some helper functions like the first example, the only modification is that the new function will generate an URL for a one type only.

The code of the buttons will be like:

$(".commands button[data-type]").each(function() {
  var button = $(this);
  var type = button.data("type");

  button.off("click").click(function(e) {
    e.preventDefault();
    var plugin = track.findPluginByName("RemoteContent");
    plugin.options.url = function(track, page, perPage) {
      // URL with the selected type
      return urlToEchoServer(track, page, perPage, type);
    }

    plugin.reload();
  });
});

Loading content ahead of time

The "prefetchPages" optimizes the load of pages, it will load some pages before the user action so that when the user click the "next" button it will paginate instantly without the load time. This example uses the same structure of the other examples with three differences:

1º it enables the "prefetchPages", in this example with 2 pages ahead of time

// ...
track.install(new SilverTrack.Plugins.RemoteContent({
  url: urlToEchoServer,
  process: processor,
  prefetchPages: 2,
  // ...
});

2º and 3º it avoids the loading markup when the page is prefetched.

// ...
track.install(new SilverTrack.Plugins.RemoteContent({
  // ...
  beforeSend: function(track, jqXHR, settings, opts) {
    if (opts.prefetch) {
      return;
    }

    $(".loading", track.container.parent()).fadeIn();
  },

  beforeAppend: function(track, items, opts) {
    if (!!opts.prefetch) {
      return;
    }

    $(".loading", track.container.parent()).hide();
  },

  // ...
});

Take a look at the network tab of your browser to follow the requests.