JavaScript: How to display a week of dates at a time

I am working on a FrontLoops challenge where the page displays the current week of dates. Clicking on the prev button should display the previous week of dates and clicking the next button should display the next week of dates. Currently, my code automatically puts the current date in the container for Sunday no matter what day it is. I'm still fairly new to working with date and time in JavaScript, so I would appreciate any help/direction in making this functional. https://codepen.io/savvystrider/pen/rNowMbz
2 Replies
13eck
13eck9mo ago
In your populateDates() function, add this immediately after your first line (where you copy the current date):
const sub = currDate.getDate() - currDate.getDay();
currDate.setDate(sub);
const sub = currDate.getDate() - currDate.getDay();
currDate.setDate(sub);
The .getDay() function returns a zero-indexed number of the day of the week, starting with Sunday as day 0. So what we're doing is subtracting the current day number from the current day of the month so when you loop over the day numbers you're starting with Sunday. Also, you can remove the for loop (along with your getDayNames function) with this replacement for...of loop:
for (const day of document.querySelectorAll("[data-id]")) {
day.textContent = currDate.toLocaleDateString();
currDate.setDate(currDate.getDate() + 1);
}
for (const day of document.querySelectorAll("[data-id]")) {
day.textContent = currDate.toLocaleDateString();
currDate.setDate(currDate.getDate() + 1);
}
This is iterating over the node list of elements that have a data-id attribute and setting the date appropriately. I much prefer the for...of when iterating over a specific list of items. In contrast to the more traditional for loop you don't need to set anything up (like an index) and you don't need to worry about off-by-one errors. Heck, since the container is very likely to never change you could make a const days = document.querySelectorAll("[data-id]") as a global variable so you're not making new nodes each time the function runs…but that's a bit of optimization that you probably won't need for a simple thing like this.
savvystrider15
savvystrider159mo ago
Thank you! Works now and way cleaner