Skip to content

Instantly share code, notes, and snippets.

@AndersDJohnson
Last active June 5, 2019 13:35
Show Gist options
  • Save AndersDJohnson/5904056 to your computer and use it in GitHub Desktop.
Save AndersDJohnson/5904056 to your computer and use it in GitHub Desktop.
ordinal classes in javascript - updates to come!
/**
* Updates classes on items indicating their order in repeating sets from `2` thru `options.upTo`.
* e.g. "ordinal-1-of-3" for every third item.
* Optionally filter only visible elements.
* Couldn't use :nth-of-type() pseudo-selectors, since they don't count visibility.
*/
var updateOrdinalClasses = function ($items, options) {
var defaults = {
onlyVisible: true,
upTo: 4
};
var settings = $.extend({}, defaults, options || {});
// remove all the classes
var classes = ["ordinal-odd", "ordinal-even"];
for (var i = 1; i < settings.upTo; ++i) {
$this.addClass("ordinal-" + ((i % i) + 1) + "-of-" + i);
}
if (settings.onlyVisible) {
// select visible links
$items = $items.filter(":visible");
}
// add classes again
$items.each(function (i) {
var $this = $(this);
if (i % 2 == 0) {
$this.addClass("ordinal-even");
} else {
$this.addClass("ordinal-odd");
}
for (var i = 1; i < settings.upTo; ++i) {
$this.addClass("ordinal-" + ((i % i) + 1) + "-of-" + i);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment