Question

I've been working on my online portfolio trying to create a filterable section. Basically, I'm trying to get the following result:

clicking on a tag in the filter section should display the appropriate works, hiding the rest

I'm not sure how I can achieve this, and I don't want to use a jQueru plugin. The last two lines of my code work fine, but there's something wrong elsewhere.

$('.filters li').click(function() {

    if ($(this).attr('id') == '#all') {
    $('#works ul li').animate({
        opacity : '0'
    });
    }
    else {
        $(this).trigger('show');
        $(this).trigger('hide');
    }


    $('.filters li').removeClass('current');
    $(this).addClass('current');
});

Here's the HTML code:

<ul class="filters">
<li id="all">Tous</li>
<li id="webdesign">Web Design</li>

<section id="works">
<ul>
    <li class="webdesign">
    <span class="details">
        <h4>title</h4>
        <p>skills</p>
    </span>
    <img src="http://placekitten.com/365/240" alt="">
    </li>
    <li class="wordpress">
    <span class="details">
        <h4>title</h4>
        <p>skills</p>
    </span>
    <img src="http://placekitten.com/365/240" alt="">
    </li>
</ul>
</section>
Était-ce utile?

La solution

Start by declaring our variables, and caching our selectors to both elements:

var filtr = $("#filters"), 
    works = $("#works li"), 
    curnt = "current",
    clsID = "";

Next we setup event delegation, meaning we only bind one event, yet we leverage the behavior of bubbling to listen for events that were initiated by clicking on a nested li element:

filtr.on("click", "li", applyFilter);

Lastly, we declare the behavior of our handler. In this case, we capture the id of the list item clicked (or "all" if no id exists), and we use that to filter the list items within our #works element:

function applyFilter () {
    clsID = this.id || "all";
    clsID === "all"
        ? works.removeClass(curnt).show()
        : works.not("." + clsID).removeClass(curnt).hide()
               .siblings().addClass(curnt).show();
}​​

Fiddle: http://jsfiddle.net/mrU4Y/10/

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top