How to align weekdays to dates using a table?

Viewed 163

I am working on making a working calendar. I need my dates to align with my dates (as of now, it is Wednesday 27th, yet my calendar makes it appear as Monday because the first dates are misaligned).

I know that the issue is the misaligned dates. I am struggling with figuring out a solution that would not require manual input (I want it to be automated)

var date = new Date();
// gets new date, which is the current date. 

function getMonthName(month) {
  // create array to hold name of each month
  var monthNames = new Array(12);
  monthNames[0] = "January";
  monthNames[1] = "February";
  monthNames[2] = "March";
  monthNames[3] = "April";
  monthNames[4] = "May";
  monthNames[5] = "June";
  monthNames[6] = "July";
  monthNames[7] = "August";
  monthNames[8] = "September";
  monthNames[9] = "October";
  monthNames[10] = "November";
  monthNames[11] = "December";

  // return name of specified month (parameter)
  return monthNames[month];
}

console.log(getMonthName(1)); // Februrary

var currentDay = date.getDay();
// gets the day within a week. (sunday - saturday, 0-6)

var totalDays = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
// -> (2022, 4 (May), 0 (last day of last month)).getDate(); -> 30
// console.log(totalDays);


let week0 = document.createElement("week0");
let tbody = document.querySelector("#dates");

tbody.appendChild(week0);
// for the for loop

for (day = 0; day < currentDay; day++) {
  // for first row
  // does 4 times for wed, 20/04/2022

  let new_td = document.createElement("td");
  let table_row = document.querySelector("#week0"); // selecting week0 - line 12
  table_row.appendChild(new_td); //adding to cells to row
  new_td.innerText = "";
}

// align the weekday to the date 

// for (weekDay = 0; weekDay < currentDay; weekDay++) {
  
// }

// needs to stop at 5 for friday = 1st. april 2022.



for (day = 0; day < totalDays; day++) {
  // for rest of the days

  let new_td = document.createElement("td");
  let table_row = document.querySelector(
    "#week" + parseInt((day + currentDay) / 7)
  );
  console.log(table_row);
  // "#week" + parseInt((1+3)/7), table_row = querySelector("#week + 5/7") -> week#0
  // "#week" + parseInt((4+3)/7), table_row = querySelector("#week + 5/7") -> week#1
  // parseInt() = string -> integer

  table_row.appendChild(new_td);
  // add
  new_td.innerText = day + 1;
  // changes the cell text
}

// simulate in mind


// add day view?
// https://www.youtube.com/watch?v=YL3ufzQ0QC4
// *create event using forms (for tracking locally)
// https://codepen.io/corvus-007/pen/MzEKyJ 
@import url("https://fonts.googleapis.com/css2?family=Roboto+Mono:ital,wght@0,100;0,200;0,300;0,400;0,500;1,100;1,200;1,300;1,400;1,500&display=swap");

/* 'Roboto Mono', sans-serif;  */

* {
  text-align: center;
  font-family: "Roboto Mono", sans-serif;
}

table {
  margin-left: auto;
  margin-right: auto;
  width: 100%;
  border-collapse: collapse;
}

table,
th,
td {
  border: 1px solid;
  padding: 10px 0 40px 0;
  /* padding: 61px; */
  /* text-align: right; */
}

th {
  background-color: rgb(245, 143, 143);
  color: rgb(0, 0, 0);
  font-weight: bold;

}

td:hover {
  background-color: rgb(178, 172, 187);
  color: rgb(255, 255, 255);
}

.days_of_the_week th {
  padding: 3rem;
  text-align: center;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <script src="script.js" defer></script>

    <title>Habit Tracker</title>
</head>

<body>
    <h1>HABIT TRACKER</h1>
    <h2 id="month">Month</h2>
    <table>
        <thead id="days_of_week" class="days_of_week">
            <th>Sunday</th>
            <th>Monday</th>
            <th>Tuesday</th>
            <th>Wednesday</th>
            <th>Thursday</th>
            <th>Friday</th>
            <th>Saturday</th>
        </thead>
        <tbody id="dates">
            <tr id="week0"></tr>
            <tr id="week1"></tr>
            <tr id="week2"></tr>
            <tr id="week3"></tr>
            <tr id="week4"></tr>
        </tbody>
    </table>
</body>

</html>

1 Answers

Perhaps a solution like this could work for you.

Additionally, if you are looking for a solution without the "jump" buttons and etc. you can see this fiddle I made up as well. https://jsfiddle.net/treckstar/5mzwnysh/4

let today = new Date();
let currentMonth = today.getMonth();
let currentYear = today.getFullYear();
let selectYear = document.getElementById("year");
let selectMonth = document.getElementById("month");

let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

let monthAndYear = document.getElementById("monthAndYear");
showCalendar(currentMonth, currentYear);


function next() {
    currentYear = (currentMonth === 11) ? currentYear + 1 : currentYear;
    currentMonth = (currentMonth + 1) % 12;
    showCalendar(currentMonth, currentYear);
}

function previous() {
    currentYear = (currentMonth === 0) ? currentYear - 1 : currentYear;
    currentMonth = (currentMonth === 0) ? 11 : currentMonth - 1;
    showCalendar(currentMonth, currentYear);
}

function jump() {
    currentYear = parseInt(selectYear.value);
    currentMonth = parseInt(selectMonth.value);
    showCalendar(currentMonth, currentYear);
}

function showCalendar(month, year) {

    let firstDay = (new Date(year, month)).getDay();
    let daysInMonth = 32 - new Date(year, month, 32).getDate();

    let tbl = document.getElementById("calendar-body"); // body of the calendar

    // clearing all previous cells
    tbl.innerHTML = "";

    // filing data about month and in the page via DOM.
    monthAndYear.innerHTML = months[month] + " " + year;
    selectYear.value = year;
    selectMonth.value = month;

    // creating all cells
    let date = 1;
    for (let i = 0; i < 6; i++) {
        // creates a table row
        let row = document.createElement("tr");

        //creating individual cells, filing them up with data.
        for (let j = 0; j < 7; j++) {
            if (i === 0 && j < firstDay) {
                let cell = document.createElement("td");
                let cellText = document.createTextNode("");
                cell.appendChild(cellText);
                row.appendChild(cell);
            }
            else if (date > daysInMonth) {
                break;
            }

            else {
                let cell = document.createElement("td");
                let cellText = document.createTextNode(date);
                if (date === today.getDate() && year === today.getFullYear() && month === today.getMonth()) {
                    cell.classList.add("bg-info");
                } // color today's date
                cell.appendChild(cellText);
                row.appendChild(cell);
                date++;
            }


        }

        tbl.appendChild(row); // appending each row into calendar body.
    }

}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Calendar</title>

    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"
          integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">

</head>
<body>
<div class="container col-sm-4 col-md-7 col-lg-4 mt-5">
    <div class="card">
        <h3 class="card-header" id="monthAndYear"></h3>
        <table class="table table-bordered table-responsive-sm" id="calendar">
            <thead>
            <tr>
                <th>Sun</th>
                <th>Mon</th>
                <th>Tue</th>
                <th>Wed</th>
                <th>Thu</th>
                <th>Fri</th>
                <th>Sat</th>
            </tr>
            </thead>

            <tbody id="calendar-body">

            </tbody>
        </table>

        <div class="form-inline">

            <button class="btn btn-outline-primary col-sm-6" id="previous" onclick="previous()">Previous</button>

            <button class="btn btn-outline-primary col-sm-6" id="next" onclick="next()">Next</button>
        </div>
        <br/>
        <form class="form-inline">
            <label class="lead mr-2 ml-2" for="month">Jump To: </label>
            <select class="form-control col-sm-4" name="month" id="month" onchange="jump()">
                <option value=0>Jan</option>
                <option value=1>Feb</option>
                <option value=2>Mar</option>
                <option value=3>Apr</option>
                <option value=4>May</option>
                <option value=5>Jun</option>
                <option value=6>Jul</option>
                <option value=7>Aug</option>
                <option value=8>Sep</option>
                <option value=9>Oct</option>
                <option value=10>Nov</option>
                <option value=11>Dec</option>
            </select>


            <label for="year"></label><select class="form-control col-sm-4" name="year" id="year" onchange="jump()">
            <option value=1990>1990</option>
            <option value=1991>1991</option>
            <option value=1992>1992</option>
            <option value=1993>1993</option>
            <option value=1994>1994</option>
            <option value=1995>1995</option>
            <option value=1996>1996</option>
            <option value=1997>1997</option>
            <option value=1998>1998</option>
            <option value=1999>1999</option>
            <option value=2000>2000</option>
            <option value=2001>2001</option>
            <option value=2002>2002</option>
            <option value=2003>2003</option>
            <option value=2004>2004</option>
            <option value=2005>2005</option>
            <option value=2006>2006</option>
            <option value=2007>2007</option>
            <option value=2008>2008</option>
            <option value=2009>2009</option>
            <option value=2010>2010</option>
            <option value=2011>2011</option>
            <option value=2012>2012</option>
            <option value=2013>2013</option>
            <option value=2014>2014</option>
            <option value=2015>2015</option>
            <option value=2016>2016</option>
            <option value=2017>2017</option>
            <option value=2018>2018</option>
            <option value=2019>2019</option>
            <option value=2020>2020</option>
            <option value=2021>2021</option>
            <option value=2022>2022</option>
            <option value=2023>2023</option>
            <option value=2024>2024</option>
            <option value=2025>2025</option>
            <option value=2026>2026</option>
            <option value=2027>2027</option>
            <option value=2028>2028</option>
            <option value=2029>2029</option>
            <option value=2030>2030</option>
        </select></form>
    </div>
</div>
<!--<button name="jump" onclick="jump()">Go</button>-->

<!-- Optional JavaScript for bootstrap -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
        crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"
        integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ"
        crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"
        integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm"
        crossorigin="anonymous"></script>


</body>
</html>

Related