I\'m pretty new to JavaScript but am trying to have a text change according to the time of day, and display different text based on the day.
currently, I\'m stuck figuri
You could work out when you're next open from the data, rather than hard-coding strings and logic that will likely break if you change opening times and/or days.
var data = [
{}, //Sunday - closed
{ open: 18, close: 22 }, //Monday
{ open: 18, close: 22 }, //Tuesday
{ open: 18, close: 22 }, //Wednesday
{ open: 12, close: 22 }, //Thursday
{ open: 12, close: 22 }, //Friday
{ open: 12, close: 22 }, //Saturday
];
var date = new Date();
var openingTimes = openingHours(date);
var openClosed = false; // closed by default
var hour = date.getHours()
var message = 'We are open';
// check that there are opening times for today
if (hasOpeningHours(openingTimes)){
openClosed = openingTimes.open <= hour && hour < openingTimes.close;
}
if (!openClosed){
//Work out when we next open...
if (hour < openingTimes.open){ // open later on today.
var openAt = new Date();
message = 'We open at ' + formatHours(openingTimes.open) + ' today.';
}
else {
var foundNextOpenDay = false;
var nextOpenDay;
for (var i = 1; !foundNextOpenDay && i < 7; i++){
nextOpenDay = new Date(date.setDate(date.getDate() + 1)); // Add a day
openingTimes = openingHours(nextOpenDay);
if (hasOpeningHours(openingTimes)){
foundNextOpenDay = true; // exit the for loop
message = 'We open ' + (i > 1 ? formatDay(nextOpenDay) : 'tomorrow') +
' at ' + formatHours(openingTimes.open) + '.';
}
}
if (!foundNextOpenDay){
// No longer in business!
message = 'Sorry, we are closed for business.';
}
}
}
function hasOpeningHours(openingTimes){
return openingTimes.hasOwnProperty('open') && openingTimes.hasOwnProperty('close');
}
function formatHours(hour){
var amPm = hour > 11 ? 'pm' : 'am';
var time;
if (hour === 0) { // If, for whatever reason, you open at midnight!
time = 12;
}
else {
time = hour > 12 ? hour - 12 : hour;
}
return time + amPm;
}
function formatDay(date){
var dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday'];
return dayNames[date.getDay()];
}
function openingHours(date){
var dayOfWeek = date.getDay(); // 0 is Sunday, 1 is Monday, etc...
var openingTimes = data[dayOfWeek];
return openingTimes;
}
document.getElementById('open_close').innerHTML = message;
Unlike the other answers you only have to change a time in the data and everything else will just work. Added bonus - it also has no dependency on jQuery.