I’m working for a delivery company and the boss wants me to add the daily schedule of the “delivery bus” to the website. The boss wants it to only show the schedule (“bus stops”) for the current day. While not a programer myself I found some code online and adjusted it to what I need.
So what I did is put the schedule in different divs, hid them all and use jquery to only show divs based on the date.
The thing is the way I did it, each day is a new date()
and I’d need to add about 150 lines of code for each day the bus goes on the road. So, I’m looking for a better solution, perferably to the existing code, because I sort of understand it. I’m looking into creating a array of dates, but so far I’m hitting a wall. As I said I’m not a programer. Any ideas?
Working fiddle https://jsfiddle.net/ezdv8rwL/
Just change the date if you’re not looking at it today
The JavaScript Date constructor accepts the following for dates based on numbers: new Date(year, monthIndex, day). You may be able to use a for loop to more dynamically create a bunch of dates.
I’m guessing though this is a weekly schedule, so it may be easier to set it to figure the weekday?
The
.getDay()
function gets the day as an integer, where Sunday is considered the first day (with value 0).Quick lookup:
You can replace the check
if (current.getDate() == day.getDate())
with a simpleif (schedule[today] === [name of the day)
.More advanced would be to replace all the if statements with a
switch - case
You may add as many “case” lines as you want. A common pitfall with switch-case is that the
break
is required, as a thing called fallhrough would allow to have code of multiple consecutivecase
s executed until abreak
orreturn
is reached.