I need to display different content for 15 days in a loop indefinitely with JavaScript Vanilla. So each day, I display a div with specific content and after 15 days, the process starts. Here is what I have done so far:
const Rotator = {
init(startDate) {
const todayMonth = new Date(SERVER_DATETIME).getMonth() + 1;
const todayDate = new Date(SERVER_DATETIME).getDate();
const sectionArray = [];//array of ids
const daysArray = [];//array of days to rotate
document.querySelectorAll('.ws-slide').forEach((item,index) => {
let id = item.id;
sectionArray.push(id);
});
// console.log(sectionArray);
sectionArray.forEach((item, index) => {
daysArray.push(startDate + (index * 24 * 60 * 60 * 1000));
});
// console.log(daysArray);
daysArray.forEach((item, index) => {
let newMonth = new Date(item).getMonth() + 1;
let newDate = new Date(item).getDate();
if (newMonth === todayMonth && newDate === todayDate) {
console.log(sectionArray[index])
document.querySelector(`#${sectionArray[0]}`).style.display = "none";
document.querySelector(`#${sectionArray[index]}`).style.display = 'block';
}
});
}
}
The script takes the start date and creates two arrays: one for the ids of the element and the other for the next 15 days in milliseconds. I'm able to execute the script for 15 days, but don't know how to restart the cycle dynamically unless I set up different start dates. Below I set up the restart date every 15 days for the first 90 days:
const spectrumStartDate = '6/29/2023';
let date;
let d = new Date(SERVER_DATETIME);
let slidesLength = document.querySelectorAll('.ws-slide').length;
let cycle = 24 * 60 * 60 * 1000 * slidesLength;
let mydate = new Date(spectrumStartDate).getTime(); //'6/29'
console.log("start date 6/29 " + new Date(mydate));
let mydate15 = mydate + cycle;
console.log("start date 7/14 " + new Date(mydate15));
let mydate30 = mydate15 + cycle;
console.log("start date 7/29 " + new Date(mydate30));
let mydate45 = mydate30 + cycle;
console.log("start date 8/13 " + new Date(mydate45));
let mydate60 = mydate45 + cycle;
console.log("start date 8/28 " + new Date(mydate60));
let mydate75 = mydate60 + cycle;
console.log("start date 9/12 " + new Date(mydate75));
let mydate90 = mydate75 + cycle;
console.log("start date 9/27 " + new Date(mydate90));
if (d >= mydate90) {
date = mydate90 //start date is 9/27
} else if (d >= mydate75) {
date = mydate75 //start date is 9/12
} else if (d >= mydate60) {
date = mydate60 //start date is 8/28
} else if (d >= mydate45) {
date = mydate45 //start date is 8/13
} else if (d >= mydate30) {
date = mydate30 //start date is 7/29
} else if (d >= mydate15) {
date = mydate15; //start date is 7/14
} else if (d >= mydate) {
date = mydate;//start date is 6/29
}
console.log("start date is " + new Date(date));
Rotator.init(date);
I'd greatly appreciate it if you could help me. Thank you in advance.