tags:

views:

49

answers:

2

I'm attempting to use a side navigation to display table rows by category using jQuery.

<ul class="side-nav">
<li class="head">categories</li>
    <li><a class="item" href="#">Show all</a></li>
<li><a class="accessories" href="#">Accessories</a></li>
<li><a class="books" href="#">Books</a></li>
<li><a class="electronics" href="#">Electronics</a></li>
<li><a class="dvd" href="#">Dvd</a></li>
<li><a class="misc" href="#">Misc.</a></li>
</ul>

<table>
<tr class="item misc.">
<td>1964 Jaguar model car</td>
<td>Misc.</td>
</tr>
<tr class="item dvd">
<td>Up(Pixar)</td>
<td>Dvd</td>
</tr>
<tr class="item electronics">
<td>Apple iMac</td>
<td>Electronics</td>
</tr>
</table>

Currently I'm using something like this and just repeating it for every category but these categories will eventually be added dynamically and this won't cut it. I know there's gotta be an easier way. Thanks for the help.

$('a.electronics').click(function() {
$('tr.item').hide();
$('tr.electronics').fadeIn();
});

$('a.item').click(function() {
$('tr.item').fadeIn();
});
A: 

You're going to have to somehow store the link between the hyperlink and the table row. You could either do this by:

1) Binding each one individually: This basically means having your script write out something to bind them, similar to what you have now just generated by whatever code makes your table. You'd probably want to move the functionality into a single function you'd call rather than write it out with each, but each one would need to be bound separately.

2) Using some attribute of the hyperlink. In your example you've basically used the CSS class so you could go something like:

$('.sidenav a').click(function() {
   $('tr.item').hide();
   $('tr.' + $(this).attr('class')).fadeIn();
});

But if you add another class to your a then that'll break. You could also use another attribute for this mapping, or some relationship between the ID's (EG: the A is '#electronics' and the tr is '#electronicsrow' and then on the second you'd just go $('#'+$(this).attr('id')+'row')), so that it doesn't mess with what you can do with your ability to add CSS classes to it. You could also make up your own fake attribute just to store the mapping, but as tidy as that is it won't validate.

Tim Schneider
Thanks! That was quick and very helpful.
nickespi
A: 

Here you go:

$(function()
{
    $('ul.side-nav a').click(function()
    {
       $('tr.item').hide();
       $('tr.' + $(this).attr('class')).fadeIn();       
    });
});

Working example: http://jsbin.com/eratu3

Vegard Larsen