Skip to content

Instantly share code, notes, and snippets.

@HelgeSverre
Last active February 14, 2017 08:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HelgeSverre/2234d082b9e65d36d4aa42fbf5510281 to your computer and use it in GitHub Desktop.
Save HelgeSverre/2234d082b9e65d36d4aa42fbf5510281 to your computer and use it in GitHub Desktop.
Simple class based jaavascript filtering solution using data attributes
$(".filters .filters__wrapper ul").on("click", "li", function () {
// Set clicked element as active
$(this).siblings().removeClass("active");
$(this).toggleClass("active");
// Get the class to filter by
var filterClass = $(this).data("filter").trim();
// Get the grid this filter applies to (use data-grid="#some-id-here")
var gridIdentifier = $(this)
.parent("ul")
.data("grid");
// Get grid items
var items = $(gridIdentifier).children(".grid__item");
// Show/Hide based on their class
for (var i = 0; i < items.length; i++) {
var item = $(items[i]);
if (filterClass == "*" || filterClass == "") {
item.fadeIn();
} else if (!item.hasClass(filterClass)) {
item.fadeOut(500);
} else {
item.fadeIn(500);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment