I’m trying to extend the JavaScript on a page I maintain to apply some formatting as the calendar section of the page is loaded. There’s a prexisting function called InitCalendar(month) that loads the section in response to a click.
The calendar is written as a list of days. I’d like to alter the height of <div> elements containing events based on the number of events per day. If there are two rather than one event in a day, each event needs to shrink to fit, etc.
So the intended algorithm is to:
-
Get an array of
<li>, the days in the calendar. -
For each
<li>, get a array of the<div>elements it contains -
Set the appropriate height based on the length of the
divarray.
My effort is failing with this error: “Uncaught TypeError: Cannot read property ‘style’ of undefined”
Here’s my code:
function setHeights(n, string, elems) {
// start at 1 to avoid the first element in the array.
for (var i = 1; i <= n; i++) {
var x = elems[i];
x.style.height = string;
};
};
function eventHeights() {
var ls = $(".calendar").children().children();
var n = ls.length;
for (var i = 0; i < n; i++) {
var divs = ls[i].children;
switch (divs.length) {
case 4:
setHeights(4, "27px", divs);
case 3:
setHeights(3, "52px", divs);
};
};
};
function InitCalendar(month)
{
// ... Some preexisting code to load the calendar section ...
eventHeights();
}
Here’s a fragment of the HTML to show the structure I’m working with:
<div class="calendar">
<ul>
<li>
<div>...</div>
<div>...</div>
</li>
<li>
<div>...</div>
</li>
<li>
<div>...</div>
<div>...</div>
<div>...</div>
<div>...</div>
</li>
</ul>
</div>
Help figuring this out greatly appreciated!
JavaScript arrays are 0 based, so the for loop in
setHeightsis incorrect. Note the change in the assignment ofiand the change from<=to<in the condition: