Target Dynamic HTML With jQuery

I’m working on a WordPress theme and have JS for live filtering post results based on a toggled category item. The category links are just created from wp_list_categories(); and the post list is generated with a WP_Query();

At the moment I have unique post ID’s set in the JS to make this work but to have others use the theme, I don’t want them to have to edit the JS each time they add a new category. Basically, I’d like to have the JS function and filter posts, regardless of how many categories are added.

Read More

My current markup is just like this:

<section id="sidebar">
    <ul>
        <li class="cat-item cat-item-1"></li>
        <li class="cat-item cat-item-2"></li>
        <li class="cat-item cat-item-3"></li>
    </ul>
</section>

<section id="postlist">
    <div class="1post apost"></div>
    <div class="2post apost"></div>
    <div class="3post apost"></div>
</section>

And my JS as follows:

$(".cat-item-1").click( function() {
    $('.1post').toggle('slow');
});

$(".cat-item-2").click( function() {
    $('.2post').toggle('slow');
});

$(".cat-item-3").click( function() {
    $('.3post').toggle('slow');
});

This works fine when I explicitly type it out each time for each category and post ID but I’m trying to accomplish something like:

$(".cat-item-" + (dynamic cat ID)).click( function() {
    $("." + (dynamic post ID that matches cat ID) + "post").toggle('slow');
});

Is this at all possible? I’m not the most experienced person in the world when it comes to JS so apologies if the solution is staring me in the face! I’ve added this as a Fiddle here: http://jsfiddle.net/davemcnally/5QZcw/ — Thanks in advance!

Related posts

Leave a Reply

1 comment

  1. Take a look at my solution: http://jsfiddle.net/EP96x/

    $('.cat-item').click(function () {
        $('.apost').eq($(this).index()).toggle();
    });
    

    It counts which element with class cat-item you clicked (1st, 2nd etc…) and then toggles corresponding element with the class apost.

    EDIT: As pointed out in comments, there’s certain risk of the elements coming out of order. If that’s the case there’s the need for using regexp in order to match link with the proper element:

    http://jsfiddle.net/HKkq5/

    $('.cat-item').click(function () {
        var num = $(this).attr('class').match(/cat-item-(d+)/)[1];
        $('.' + num + 'post').toggle();
    });