Liam Hannigan
Liam Hannigan

Reputation: 3

Trying to set an image to change at certain times on a loop Monday-Friday

I am wanting the below to run Monday-Friday and on the weekends display the second image (4:30pm-:8:30am) on a constant loop.

The image will display when a customer service team is available Monday-Friday 8:30am-4:30pm and will display when they are not available outside of these hours.

However I wish for it to display just } else { document.write('<img src="#IMAGE 4:30PM-8:30AM#">'); on Saturday and Sunday

var now = new Date();
var today = now.getDay();
var startTime = new Date();
startTime.setHours(08);
startTime.setMinutes(30);
startTime.setSeconds(00);
var endTime = new Date();
endTime.setHours(16);
endTime.setMinutes(30);
endTime.setSeconds(00);
console.log(startTime,now,endTime)
if (today > 0 && today < 6) {
  if (startTime < now && endTime > now) {
    document.write('<img src="#IMAGE 08:30AM-4:30PM#">');
  } else {
    document.write('<img src="#IMAGE 4:30PM-8:30AM#">');
  }
}

Upvotes: 0

Views: 45

Answers (1)

mplungjan
mplungjan

Reputation: 178350

You mean this?

var now = new Date(), startTime = new Date(), endTime = new Date();
var today = now.getDay();
var closedSign = 'image.ibb.co/mMAptU/if_18_Closed_Sign_1871435.png';
var openSign = 'image.ibb.co/f4rvYU/if_15_Open_Sign_1871431.png';

startTime.setHours(8, 30, 0);
endTime.setHours(16, 30, 0);

// open when now is within start and endTime, Mon to Fri
var src = (today > 0 && today < 6) &&
  (now >= startTime && now <= endTime) ? openSign : closedSign; // ternary

document.write('<img src="' + src + '">');

Upvotes: 1

Related Questions