Gorgon_Union Gorgon_Union - 7 months ago 9
HTML Question

Loading dynamic calendar to start on correct day of the month

I'm trying to get a calendar to load the days of the month on the correct starting day of whichever year is selected by user. Right now the form loads the correct month and number of days for each month, but it starts on Sunday[0], when for instance, in April, the 1st is on Friday of week 1.

I've been stuck on this for a few days, and I can't figure out what or where i'm supposed to put a loop that makes it start on the correct day, and have the previous months days blank.

var daysOfTheWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

function showCalendar (mth, yr)
{
var firstDayOfMonth = mth + "/1/" + yr;
var d = new Date ( firstDayOfMonth);
var numberOfDaysInMonth = daysInMonth (d);
var firstDayOfWeek = d.getDay();

var str = "<ul>";
str += "<li>Number of days in the month: " + numberOfDaysInMonth + "</li>";
str += "<li>First day of the week: " + firstDayOfWeek + " (" + daysOfTheWeek[firstDayOfWeek] + ")</li>";
str += "</ul>";

calstr = "";
var maxCalDays = 35;
for(var i =0; i<numOfDaysInMonth; i++) {
// if there are 7 cells create string - row
if (i % 7 == 0 && i > 0) {
calstr += "<div class='row'>";
}
// increments through each cell - making up each row
calstr += "<div class='calCell'>" + (i + 1) + "</div>";
if (i % 7 == 0 && i > 0) {
calstr += "</div>";
}
}
$("#results").append(calstr);


Here is the what it looks like running.

JSFiddle

Answer

I edited your jsFiddle:

You just have to skip the days days before the first day with:

 for(var j = 0; j < firstDayOfWeek; j++){
    calstr += "<div class='calCell empty'></div>";
 }

e.g. set css classes like this:

.calCell.empty {
    border: none;
}

And then add these days to your modulo operation to have the right 7 days line break:

var maxCalDays = 35;
for(var i = 0; i < numOfDaysInMonth; i++) {
    // if there are 7 cells create string - row
    if((i + firstDayOfWeek) % 7 ==0 && i>0) {
        calstr += "<div class='row'>";
    }
    ...
}

Also you have to disable selecting of this empty cells with replacing your selectors .calCell with .calCell:not(.empty). E.g.:

$(".calCell:not(.empty)").click(function() {
    changeColor($(this));
});

I guess you only want to show old with $("#results").html("")