Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery data attribute click event

Tags:

jquery

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>
like image 379
benhowdle89 Avatar asked Jan 16 '12 23:01

benhowdle89


2 Answers

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/

like image 170
Liam Avatar answered Oct 13 '22 00:10

Liam


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/

like image 44
user1106925 Avatar answered Oct 12 '22 23:10

user1106925