Reputation: 2530
I'd like to use this show/hide function by data-attributes instead of class, but I'm having a hard time getting the syntax right.
I know that it's something like this $("li[data-color=" + this.value + "]").show();
but I haven't been able to get it to work and/or modify the function so that it works.
I'm using the function to filter clothing by various attributes (i.e. color, product-category, occasion, etc.), and I've posted a fiddle with a simple example here: http://jsfiddle.net/chayacooper/WZpMh/4/
$('#filterOptions li a').click(function () {
var ourClass = $(this).attr('class');
$('#filterOptions li').removeClass('active');
$(this).parent().addClass('active');
if (ourClass == 'all') {
$('#content').find('.item').show();
} else {
$('#content').find('.item:not(.' + ourClass + ')').hide();
$('#content').find('.item.' + ourClass).show();
}
return false;
});
Upvotes: 2
Views: 1154
Reputation: 5962
Please see this fiddle for a working example: http://jsfiddle.net/Cr2cY/
$(document).ready(function () {
$('#filterOptions li a').click(function () {
// fetch the class of the clicked item
var ourDataAttr = $(this).data('color');
// reset the active class on all the buttons
$('#filterOptions li').removeClass('active');
// update the active state on our clicked button
$(this).parent().addClass('active');
if (ourDataAttr == 'All') {
// show all our items
$('#content').find('.item').show();
} else {
// hide all elements that don't share ourClass
$('#content').find('.item:not([data-color="' + ourDataAttr + '"])').hide();
// show all elements that do share ourClass
$('#content').find('.item[data-color="' + ourDataAttr + '"]').show();
}
return false;
});
});
Note that you were comparing 'all' with 'All' in your fiddle, which will not match.
Upvotes: 5