I have the following Code:
<table>
<tr class="odd"><td>Entry 1</td></tr>
<tr class="even clickable" onclick="showHide('sub2')"><td>> Entry 2</td></tr>
<tr class="even" id="sub2">
<td><ul><li>Information 1</li><li>Information 2</li></ul></td>
</tr>
<tr class="odd"><td>Entry 3</td></tr>
<tr class="even"><td>Entry 4</td></tr>
</table>
and the following js:
function showHide(id) {
var el = document.getElementById(id);
if( el && el.style.display == 'none')
el.style.display = 'block';
else
el.style.display = 'none';
}
with this css:
tr.odd{
background-color: #dedede;
}
tr.even{
background-color: #7ea9ff;
}
tr.clickable{
cursor: pointer;
}
tr.clickable:hover{
color: white;
}
tr[id^="sub"]{
display: none;
}
Could someone please tell me, why it doesn't work? I'm trying to show / hide onclick the row with the id="sub2"
example in jsfiddle
Open your debug console when you run your code, and you will get the message "ReferenceError: showHide is not defined".
If you place your html and javascript inside a file and run that that particular issue is resolved. It has something to do with the order with which jsfiddle processes sources.
Secondly, you are trying to get an element by id, but give it the class name - that does not make sense. By giving elements id's and using that it works.
But this is very unwieldy, and just serves to explain why it did not work. You are better off using jQuery as raphael said.
edit: replaced html with link
function showHide(id) {
var el = document.getElementById(id);
if( el && el.style.display == 'block')
el.style.display = 'none';
else
el.style.display = 'block';
}
First of all, in your JSFiddle example, the function is wrapped into a domready event. You should change the wrap of your JavaScript to No wrap - in body. This can be set up in the second dropdown in the left bar. Your function won't be accessible otherwise.
Then, the second line in your JavaScript searches for an element with an ID - but your document does not contain any ID's, it contains classes. document.getElementById
can only find elements by their IDs.
I would suggest that you use jQuery for this task. With jQuery, the task can be solved like this:
HTML:
<table>
<tr class="odd"><td>Product 1</td></tr>
<tr class="trigger"><td>> Product 2</td></tr>
<tr class="even"><td> Information 1</td></tr>
<tr class="even"><td> Information 2</td></tr>
<tr class="odd"><td>Product 3</td></tr>
<tr class="even"><td>Product 4</td></tr>
</table>
JavaScript:
$(document).ready(function() {
$(".trigger").click(function() {
$(".even").toggle();
});
});
JSFiddle
jQuery Toggle Documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With