Nathan S Nathan S - 4 days ago 6
Javascript Question

Collapsable table Javascript - changing initial view

I have a calendar that is made up of a

<table>
for each month. I am using Javascript to expand/collapse each month.

Javascript:

$(function() {
var $month = $('.month');
$month.find("tr").not('.monthLabel').hide();
$month.find("tr").eq(0).show();

$month.find(".monthLabel").click(function(){
$month.find('.monthLabel').not(this).siblings().fadeOut(500);
$(this).siblings().fadeToggle(500);
}).eq(0).trigger('click');
});


HTML:

<table border="0" cellpadding="0" class="month jan">
<tr class="monthLabel">
<th scope="col" colspan="7">
<h3>January</h3>
</th>
</tr>
<tr class="weekLabel">
<th class="sun" scope="col" abbr="Sunday">Sun</th>
<th class="mon" scope="col" abbr="Monday">Mon</th>
etc...
</table>


It works fine, but right now, it defaults with the first table (January) expanded, and the rest collapsed. I would like it to, instead, default to the current month expanded and the rest collapsed. Is there a way I can do this without completely reformatting the tables? This would be ideal, as there are about 40 of these calendars that are automatically generated using VBasic. If possible, I'd like the actual table HTML to remain unchanged.

Answer

I presume the reason it defaults to January is that you are firing the click event on the the first row (January) with -

...eq(0).trigger('click');

If you would like to default to a different month, just supply a different row number -

// for february
...eq(1).trigger('click');

Personally, I would extract the function out so it could be used outside a click event.

function showMonth( monthName ){ .... }
Comments