Hi,
I have a table like this:
<table class="shoplist">
<tr>
<td>name</td><td><a href="#">Info</a></td>
</tr>
<tr class="details"><td colspan="2"><div>details</div></td>
</tr>
...
</table>
and the following script:
$(function() {
$('.shoplist a').click(function() {
$(this).parent().parent().next('.details').children('td').children('div').slideToggle(600);
return false;
});
});
The above works but seems overly complicated. Can anyone suggest a better way to do it?
Thanks,
It seems quite easy… not too many code
Maybe try without a table and with <li> lists instead ?
Ah, well this is a simplified version of the table. There’s actually two more columns and I thought about doing it as a list but a table really is the best option.
Don’t have a clue to get this more simplified, as I’m not so experienced in jquery etc…
But, maybe you could do this with some sorth of array and a for loop, running through your links, giving them a function.
<table id="shoplist">
<tr>
<td>name</td><td><a href="#">Info</a></td>
</tr>
<tr class="details"><td colspan="2"><div>details</div></td>
</tr>
...
</table>
// JS:
links = document.getElementById('shoplist').getElementsByTagName('a');
divs = document.getElementById('shoplist').getElementsByTagName('div');
for (var i=0; i < links.length; i++) {
links[i].onclick = divs[i].doSlideToggleFunction();
}
// ..... needs to be worked out some more
At the end, my solution will be more complicated I guess
Have you read the tree traversal documentation?
$(this).parent('tr').next('.details').children('div').slideToggle('slow');
A pure Javascript solution would work but defeats the point of using jQuery really, but thanks for the suggestion.
Paul - yes I’ve tried a few of them but without much luck. If I modify your suggestion to use closest instead of parent it nearly works but I still need another .children(‘td’):
$(this).closest('tr').next('.details').children('td').children('div').slideToggle('slow');
It’s one less selector at least but still seems like too many. But it works so it’s not critical, I just figured there must be a more efficient way.
Oh yes, I should have seen it before.
Use a context selector, so that you select the div that is within the the context of the next details element.
$('div', $(this).closest('tr').next('.details')).slideToggle('slow');
So, starting from that details element, you find the selector, and then slide the result.
Ah, excellent, that works. I didn’t know about about context selectors so I’ve learnt something today. Thanks Paul!