I have made a quick fiddle to outline my problem: http://jsfiddle.net/mYdxw/
I'm trying to click on a div, grab its data attribute and show its corresponding set of divs.
Can anyone spot why it isn't doing this currently?
JS
$(document).ready(function() {
$('.categoryItems').click(function() {
$('.itemLinks').hide();
var target_category = $(this).attr('data-target_category');
$('.itemLinks [data-category=' + target_category + ']').show();
});
});
HTML
<div id="categories">
<div data-target_category="html-site-templates" class="categoryItems">HTML Site Templates</div>
<div data-target_category="jquery-plugins" class="categoryItems">jQuery Plugins</div>
<div data-target_category="tumblr-themes" class="categoryItems">Tumblr Themes</div>
<div data-target_category="wordpress-themes" class="categoryItems">WordPress Themes</div>
</div>
<div id="content">
<a class="itemLinks" data-category="tumblr-themes" href="/tumblr-themes/mini-tumblr-theme/">Mini Tumblr Theme</a>
<a class="itemLinks" data-category="jquery-plugins" href="/jquery-plugins/randomr-jquery-plugin/">Randomr jQuery Plugin</a>
<a class="itemLinks" data-category="wordpress-themes" href="/wordpress-themes/redux-wp-theme/">Redux WP Theme</a>
</div>
Just to improve on the code, jQuery provides .data() to retrieve the value of the dataset so instead of using attr() use data()
var target_category = $(this).data('target_category');
DEMO: http://jsfiddle.net/mYdxw/28/
This...
$('.itemLinks [data-category=' + target_category + ']').show();
should be this...
$('.itemLinks[data-category="' + target_category + '"]').show();
The space is interpreted as a descendant selector, but the data-category
is directly on the itemLinks
element, not on a descendant.
I also added quotes around the value of the attribute selector. The API requires it.
DEMO: http://jsfiddle.net/mYdxw/11/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With