Generate a HTML table for use as a calendar

This javascript function generates a table with a cell per day of the year. Months are on separate rows.

Each cell within the table has an id using the format m-d (i.e. 4th of May is 5-4).

Details

  • Language: Javascript

Snippet

function genCalendar(year){
    date = new Date(year + "-01-01");

    // Set this to the ID of the element you want to write into
    cont = document.getElementById('cal-container');

    d = 1;
    max_d = 365;
    month = 0;

    t1 = document.createElement('table');
    t1.className = "dates";
    tr = document.createElement('tr');
    tr.appendChild(document.createElement("th"));
    for (var i=1; i<32; i++){
        th = document.createElement("th");
        if (i<10){
            th.innerHTML = "0" + i;
        }else{
            th.innerHTML = i;
        }
        tr.appendChild(th);
    }

     // Iterate through days
    for (var d=0; d < max_d; d++){
        m = date.getMonth()+1;
        if (m != month){
            t1.appendChild(tr);
            tr = document.createElement("tr");
            td = document.createElement("td");
            td.innerHTML = date.toLocaleString('default', { month: 'short' });
            tr.appendChild(td);
            month = m;
        }

        td = document.createElement("td");
        td.id = m + "-" + date.getDate();
        td.className = "present"

        tr.appendChild(td);
        date.setDate(date.getDate() + 1);
    }

    t1.appendChild(tr);

    cont.appendChild(t1);
}

Usage Example

<html>
<head>
    <script type="text/javascript" src="/path/to/script.js"></script>
    <link rel="stylesheet" href="/some/other/styles.css" />
    <style type="text/css">
    td.present {
        background-color: lightgray; 
        border: 1px solid; 
        color: #000
        } 
    table.dates{
        width: 50%; 
        margin: 30px;
        }
    </style>
</head>
<body>
<div id="cal-container"></div>
<script type="text/javascript">genCalendar('2024')</script>
</body>
</html>