1.0.1 • Published 7 years ago

voogpagination v1.0.1

Weekly downloads
2
License
MIT
Repository
github
Last release
7 years ago

voogPagination

voogPagination is a jQuery-based front-end pagination plugin for the Voog CMS. It utilizes Voog's public API (https://www.voog.com/developers/api) and can be used to paginate elements, articles and comments. This plugin is js only, i.e. there are no default themes or CSS styles included.

Getting started

You can either use a package manager or download the latest release from this GitHub repo.

# Bower
bower install --save voogpagination

# NPM
npm install voogpagination

Initializing

<div class="js-paginatedArticles"></div>
<script>
  $(document).ready(function() {
    var settings = {
      parentId: {{page.id}}
    };
    $('.js-paginatedArticles').voogPagination(settings);
  });
</script>

Settings

OptionTypeDefaultDescription
ajaxErrorHandlerfunctionnullCalled on ajax request errors. See the source and examples for reference.
cachePagesbooleantrueWhether to cache the fetched items.
dateFormatterfunctionnullOverrides the itemTemplates function used for date formatting. See examples section for more info.
defaultNotificationsObject{}Contains the notification settings. All notifications are rendered inside the messageTemplate.
defaultNotifications.noItemsstring'No items to display.'Shown when there are no items to render.
defaultNotifications.errorstring'Oops! Something went wrong! <br> Try refreshing the page or check back soon'Shown as a general error message. May contain html tags.
enablePageUrlsbooleantrueWhether to display pagination queries in the url.
eventNameSpacestring'.vp'Used to namespace voogPagination's events.
hashPrefixstring'page-'Change the hash prefix. Only applicable if the urlFormat is set to 'hash'.
hashSuffixstring''Change the hash suffix. Only applicable if the urlFormat is set to 'hash'.
initClassstring'voogPagination-initialized'Html class attribute added to the pagination wrapper on initialization.
itemTemplatefunctionnullTakes two aguments - item (either article, comment or element object) and dateFormatter (function). Has to return a string. See the examples section and the source for more info.
itemWrapperfunctionnullUseful for when you don't want to override the entire item template, but just want to wrap every item in some html. See the examples section for more info.
itemTypestring'article'Which type of items to paginate, possible values are: 'article', 'element' and 'comment'.
messageTemplatefunctionnullUsed for rendering notifications. See the examples section for more info.
navigationObject{}Contains the navigation settings.
navigation.containerstringnullclassName or id of the container into where the navigation should be rendered. By default, navigation is rendered at the bottom of the items' parent element.
navigation.totalLengthnumber9The total number of navItems to render excluding thr first and last page links.
navigation.edgeLengthnumber1How many edge navitems should be rendered. ScreenShot
parentIdstringnullId of the page from where the paginated items should be fetched, e.g. your blog id or elements page id. If you do not provide an id, all articles or elements will be fetched.
perPagenumber12How many items to display per page.
queryKeystring'page'Change the query prefix. Only applicable if the urlFormat is set to 'singleQueryVar'.
queryVarsstringnullUseful for filtering and sorting paginated items. See Voog's documentation for all the possible values.
renderItemsOnFirstFetchbooleantrueWhether to render the paginated items on initialize. You might want to set this to false if you are already rendering the items in your template. See the examples for more info.
requestUrlBuilderfunctionnullUsed to override defaultRequestUrlBuilder. See the source for more info.
startingPagenumber1Which page to display at start.
urlFormatstring'fullQuery'In which format to display the query portion of the url. Possible values: 'fullQuery', 'singleQueryVar', 'hash'.
useHistoryPushStatebooleantrueWhether to use browsers history push state api to keep reference of previous queries and enable the browsers back and forward button functionality.

Methods

You can call methods through the voogPagination instance. e.g:

$('.js-pagedArticles').voogPagination('goToPage', 4);
MethodArgumentDescription
currentInstanceReturns the current voogPagination instance.
goToPagetarget: intGo to page by number.
goToNextPageGo to the next page.
goToPrevPageGo to the previous page.
goToFirstPageGo to the first page.
goToLastPageGo to the last page.
destroyRemove all the DOM nodes that were created by the current instance.
refreshRerender everything.

Events

EventParamsDescription
beforeUrlUpdateevent, voogPagination, {query, pageNr, urlFormat}Triggered before updating the url.
afterUrlUpdateevent, voogPagination, {query, pageNr, urlFormat}Triggered after updating the url.
fetchStartevent, voogPagination, {requestUrl, pageNr}Triggered before the ajax request.
fetchDoneevent, voogPagination, {res, status, xhr}Triggered in the jQuery ajax done callback.
fetchFailevent, voogPagination, {xhr, status, errorThrown}Triggered in the jQuery ajax fail callback.
beforeRenderevent, voogPagination, paramsTriggered before rendering items and nav.
initializedevent, voogPaginationTriggered after the plugin has been initialized.
afterRenderevent, voogPagination, paramsTriggered after rendering the items and nav.
beforeDestroyevent, voogPaginationTriggered before executing the destroy method.
afterDestroyevent, voogPaginationTriggered after executing the destroy method.

Examples

Paginating articles

<div class="js-paginatedArticles"></div>
<script>
  $(document).ready(function() {
    $('.js-paginatedArticles').voogPagination({
      parentId: {{page.id}},
    });
  });
</script>

Paginating comments

<div class="js-paginatedComments"></div>
<script>
  $(document).ready(function() {
    $('.js-paginatedComments').voogPagination({
      itemType: 'comment',
      parentId: {{article.id}}
    });
  });
</script>

Paginating elements

<div class="js-paginatedItems"></div>
<script>
  $(document).ready(function() {
    $('.js-paginatedItems').voogPagination({
      itemType: 'element',
      parentId: {{page.id}}
    });
  });
</script>

Custom date formatting

Vanilla js

var settings = {
  dateFormatter: function(dateString) {
    var date = new Date(dateString);
    var day = date.getDate();
    var month = date.getMonth() + 1;
    var year = date.getFullYear();
    if (day < 10) {
      day = '0' + day;
    }
    if (month < 10) {
      month = '0' + month;
    }
    return day + '.' + month + '.' + year;
  }
}

With moment.js

var settings = {
  dateFormatter: function(dateString) {
    return moment.utc(item.values.datetime).format('DD.MM.YYYY');
  }
}

Custom notifications

var settings = {
  defaultNotifications: {
    noItems: 'There are no comments yet',
    error: 'Something went bork. <br> Try refreshing the page or check back soon'
  }
}

Ajax error handling

var settings = {
  ajaxErrorHandler: function (renderer, messageTemplate, data) {
    console.log(data);
    renderer(messageTemplate('Some witty and unhelpful error message', 'error'));
  }
}

Custom item templates

A custom template for elements

var settings = {
  itemTemplate: function (item, dateFormatter) {
    var title = '<div class="eventTile_title">' + item.title + '</div>';
    var category = '<div class="eventTile_category">' + item.values.category + '</div>';
    var date = '<div class="eventTile_info">' + dateFormatter(item.values.datetime) + '</div>';
    var location = '<div class="eventTile_location">' + item.values.location + '</div>';
    var button = '<div class="eventTile_button"><a href="' + item.public_url + '">Read more</a></div>';
    var templateString = '<div class="eventTile ' + item.values.category + '">' +
      title +
      category +
      date +
      location +
      button +
      '</div>';
    return templateString;
  }
}

Custom message templates

var settings = 
  messageTemplate = function (message, type) {
    type = type || 'info';
    var typeClass = 'notification-info';
    if (type === 'error') {
      typeClass = 'notification-error';
    }
    var templateString = '<div class="message ' + typeClass + '">' +
      message +
      '</div>';
    return templateString;
  }
}

Wrapping paginated items

var settings = {
  itemWrapper: function (item, index) {
    return '<div class="col-sm-4" data-item-nr="' + index + '">' + item + '</div>';
  }
}

Navigation settings

var settings = {
  navigation: {
    container: '.js-pageNav',
    totalLength: 6,
    edgeLength: 1
  }
}

Sorting and filtering

<div class="catFilter js-eventFilter">
  <label class="catFilter_item" for="category1">
    <input id="category1" type="radio" value="category-1" name="catFilter">
    Category 1
  </label>
  <label class="catFilter_item" for="category2">
    <input id="category2" type="radio" value="category-2" name="catFilter">
    Category 2
  </label>
  <label class="catFilter_item" for="category3">
    <input id="category3" type="radio" value="category-3" name="catFilter">
    Category 3
  </label>
</div>
$('.js-eventFilter input').each(function (index, element) {
  $(element).change(function () {
    // Get current voogPaginations instance
    var paginationInstance = $('.js-pagedItems').voogPagination('currentInstance');

    // Update the settings dynamically
    paginationInstance.options.queryVars = 'q.element.values.category.$matches=' + 
      $(this).val() +
      '&q.element.values.datetime.$gteq=' +
      moment().format('YYYY-MM-DD') +
      '&s=element.values.datetime.$asc';

    // Fetch the first page using the new query vars.
    $('.js-pagedItems').voogPagination('goToFirstPage');
  });
});

Pre rendering in liquid

<div class="events js-paginatedEvents">
  {% elementscontext edicy_model="Event" %}
    {% for event in elements %}
      <div class="eventTile {{ event.category }}">
        <div class="eventTile_title" data-mh="eventTile">{{ event.title }}</div>
        <div class="eventTile_category" data-mh="eventTile">{{ event.category }}</div>
        <div class="eventTile_info" data-mh="eventTile">{{ event.datetime | date: "%Y.%m.%d %H:%M" }}</div>
        <div class="eventTile_button" data-mh="eventTile">
          <a href="{{ event.url }}">Read more</a>
        </div>
      </div>
    {% endfor %}
  {% endelementscontext %}
<div>
<script>
  $(document).ready(function() {
    $('.js-paginatedEvents').voogPagination({
      itemType: 'element',
      parentId: {{page.id}},
      renderItemsOnFirstFetch: false
    });
  });
</script>

Browser support

BrowserVersion
ChromeLatest
FirefoxLatest
IE10+
EdgeLatest
Safari6.1

Dependencies

jQuery 1.7

License

Copyright (c) 2017 Mats-Joonas Kulla

Licensed under the MIT license.

1.0.1

7 years ago

1.0.0

7 years ago