EDIT: okay I put everything in the script tag in a
$(document).ready(function) {
So now the evenTd's do hide.
I have a table and the code is below
<table>
<tr>
<td>itemOne</td>
<td class="evenTd">itemTwo</td>
</tr>
</table>
Now, I want it so that at the beggining, the first td is the only td which is visible (anything in evenTd should not be visible). After that, I want it so that when you click the first td (itemOne) then itemTwo slides and appears. So far I have
$(document).ready(function() {
$('.evenTd').hide();
});
and it is hiding the evenTd's, however, now the td's which don't have the evenTd class are taking up the entire screen. How do I make it so that the layout doesn't change?
If this is the entirety of your code, and this appears before the relevant elements (whether in the head
or body
elements, the problem is that the script is run before the DOM nodes exist.
Therefore, you can either place this in $(document).ready()
:
<script>
$(document).ready(function(){
$('.evenTd').hide();
});
</script>
Or place the script after the elements, in the HTML, upon which you want to act.
<body>
<table>
<tr>
<td>itemOne</td>
<td class="evenTd">itemTwo</td>
</tr>
</table>
<script>
$('.evenTd').hide();
</script>
</body>
Do bear in mind, though, that adding and removing individual table cells is likely to cause layout problems, it's probably better to hide the descendant elements of the relevant td
, rather than the td
itself.
For example, given the current HTML:
<table>
<tr>
<td>itemOne</td>
<td class="evenTd"><div>itemTwo</div></td>
</tr>
</table>
And:
$(document).ready(function(){
$('.evenTd').hide();
});
This gives: demo, causing the single visible td
to take up the whole row-space.
Using the above HTML with the following jQuery:
$(document).ready(function(){
$('.evenTd div').hide();
});
This gives: demo, which still demonstrates layout-changes (because there's no visual content to show inside of the td
), but the td
remains visible (so it's a marginally-smaller change).
The following jQuery simply makes the content of the td
'hidden' (so it's not visible on the page, but is still 'there' taking up space in the document's flow):
$(document).ready(function(){
$('.evenTd div').css('visibility','hidden');
});
This gives: demo.
I would, however, prefer, certainly if this visibility is to be restored at some point, to add, or remove, a class on the td
itself, and use CSS to address the specifics of each state:
$(document).ready(function(){
$('.evenTd').addClass('hidden');
$('tr').on('click', 'td.evenTd', function(){
$(this).toggleClass('hidden');
});
});