I have a comparison table that has about 20 items. I would like when a link is clicked it will show more information on that item. I can do this by using the following function:
$(function(){
$('.show').click(function() {
$('#keywords').fadeIn('slow');
});
});
However as I mentioned there are twenty items and repeating the above code could get cumbersome.
How do I create a function that would show the div below the link that is clicked? On top of that if a div is open or visable and another item is clicked I want the other item to close or fade out and then the other to show.
Here is my HTML for part of the page:
<tr class="second">
<td class="cat" style="width: 33%;">
<div>
<a class="show" href="#"> Mobile Keywords</a>
</div>
<div id="keywords" class="hide">
p>Info Here</p>
</div>
</td>
<td style="width: 33%;">
<i class="icon-ok"></i>
</td>
<td class="" style="width: 33%;">
<i class="icon-ok"></i>
</td>
</tr>
<tr class="second">
<td class="cat" style="width: 33%;">
<div>
<a class="show" href="#">Another Category</a>
</div>
<div id="category-2" class="hide">
p>Info Here</p>
</div>
</td>
<td style="width: 33%;">
<i class="icon-ok"></i>
</td>
<td class="" style="width: 33%;">
<i class="icon-ok"></i>
</td>
</tr>
I assume this can be done using the this property but I do not know how to implement this as I am not familiar enough with JS.
To summarize: How do I have a link in this table that will be clicked and then the link shows the appropriate div without having to create a repeat the code for every item?
Try
Fiddle
edit: Added hide functionality as requested in the question.
Explanation
In the code above,
thisreferences the element that triggered the click event handler (the clicked anchor element).Then,
thisis wrapped inside a jQuery object and we traverse the DOM tree up to a common ancestor using the.closestmethod, from there we find the hidden element to display.The
$('.hide').hide()in the first line is self-explanatory, it hides all elements with thehideclass before animating thefadeInof the one to be displayed.