Link to home
Start Free TrialLog in
Avatar of hrhs
hrhsFlag for United States of America

asked on

Business Hours text according to time and/or day

I must have tried a 100 variations of this code and can't seem to get it right. I feel like I'm walking further off the playing field.

I want to display a message on our pages that show whether our business is open or closed depending on time and/or day.

Here is my current code.

<script type="text/javascript">
var today = new Date()
var open = ("We're open today from 9am - 5pm</span>");
var closed = ("We're closed and will open again tomorrow 9am - 6pm</span>");
if (today == 0) display.innerHTML = 'closed';
if (today.getHours() >= 9 && today.getHours() < 18) {
    display.innerHTML = 'open';
} else {
    display.innerHTML = 'closed';
}
</script>

Open in new window


and the HTML I'm currently using.

<div><span id="display"></span></div>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Shaun Kline
Shaun Kline
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You need to update display after it comes into existence.  To do this move your <script> tag after the closing <body> tag OR wrap your code in a function and have it execute upon window load (see below):

<script type="text/javascript">
window.onload=start;

function start(){
var display = document.getElementById("display");
var today = new Date()
var open = ("We're open today from 9am - 5pm");
var closed = ("We're closed and will open again tomorrow 9am - 6pm");
if (today == 0) display.innerHTML = 'closed';
if (today.getHours() >= 9 && today.getHours() < 18) {
    display.innerHTML = 'open';
} else {
    display.innerHTML = 'closed';
}
}
</script>

Open in new window