Dave Lalande
Dave Lalande

Reputation: 194

Business Open/Closed text on page according to time

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>

and the HTML I'm currently using.

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

Upvotes: 2

Views: 1967

Answers (1)

Josh Beam
Josh Beam

Reputation: 19772

Try this (see the jsfiddle):

var today = new Date(),
    open = "We're open today from 9am - 5pm",
    closed = "We're closed and will open again tomorrow 9am - 6pm",
    display = document.getElementById('display');

if (today.getHours() >= 9 && today.getHours() < 18) {
    display.innerHTML = open;
} else {
    display.innerHTML = closed;
}

HTML:

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

I assume your problem was that it was displaying "open" or "closed" in the div, when it should be displaying either "We're open today from 9am - 5pm" or "We're closed and will open again tomorrow 9am - 6pm". The issue was that you were referencing the variables open and closed as strings.

Upvotes: 3

Related Questions