I want to change background image by time of day - javascript

I want to change background image during particular part of day using JavaScript. So, i want from 6:00 to 20:00 daytime pic and from 20-06 night time pic. I am learning JS last couple of months so i m quite new to this.I created clock also.
I tried last days by Google it, still nothing, no solution. Please help.
My html :
<div class="banner">
<div class="image-day" id="img-day"></div>
<div class="image-night" id="img-night"></div>
</div>
CSS:
.banner {
min-height: 100vh;
position: relative;
display: grid;
place-items: center;
text-align: center;
}
.image-day {
position: absolute;
background: url(../images/bluesky.jpg)no-repeat center center/cover;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.image-night {
position: absolute;
background: url(../images/nightime.jpg)no-repeat center center/cover;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
JS clock :
setInterval(displayClock, 500)
function displayClock() {
var time = new Date();
var hrs = time.getHours();
var min = time.getMinutes();
var sec = time.getSeconds();
if (hrs > 12) {
hrs = hrs + 0;
}
if (hrs == 0) {
hrs = 12;
}
if(hrs < 10) {
hrs = '0' + hrs;
}
if (min < 10) {
min = '0' + min;
}
if (sec < 10) {
sec = '0' + sec;
}
document.getElementById('clock').innerHTML = hrs + ':' + min + ':' + sec;
}

You can change css properties of a dom element by using the style property like :
<DOM element>.style.<css property> = <value>
In your case to change the background image you may use something like this :
document.querySelector(".banner").style.backgroundImage="url('../images/nightime.jpg')"
Since the display clock method is already running every 5 seconds you may add the following to check if hour is greater than 6 and less than 20
if(time.getHours()>=6&&time.getHours()<20)
{
document.querySelector(".banner").style.backgroundImage="url('../images/bluesky.jpg')";
}else{
document.querySelector(".banner").style.backgroundImage="url('../images/nightime.jpg')"
}
Find a demo in this bin : demo . Open the demo and try changing your system time

Related

Changing a HTML element at a certain time and date

I have an open and closed indicator (Thanks to those who helped me!) that shows I am open from 8:00 AM to 10:00 PM and from 10:00 PM to 8:00 AM I am closed, but it shows this even on a weekend when I am not open. Can you help me make the Javascript say I am closed when it is a weekend and on a holiday like December 24-25? Below will be my current code. Thanks!
Javascript:
var messageElement = document.getElementById("message");
var circleElement = document.getElementById("circle");
const refreshStatus = () => {
// Set the current time
let currentDate = new Date().getHours();
// If the time is between 8 am and 10 pm
if (currentDate >= 8 && currentDate <= 21) {
// Update text and add classes
messageElement.innerHTML = "We are open until 10 PM";
circleElement.className = 'open-circle';
messageElement.className = 'open-p';
} else {
// 21 pm to 8 am
messageElement.innerHTML = "We are closed until 8 AM";
circleElement.className = 'closed-circle';
messageElement.className = 'closed-p';
}
}
// run when starting
refreshStatus();
// updates every 8 seconds
setInterval(refreshStatus, 8000);
CSS:
/* Start indicator CSS */
.open-circle {
position: relative;
top: 23rem;
height: 1.5625rem;
width: 1.5625rem;
background-color: #00BF13;
border-radius: 50%;
display: inline-block;
}
.open-p {
position: relative;
top: 23rem;
color: #00BF13;
font-weight: bold;
display: inline-block;
width: 8rem;
}
.closed-circle {
position: relative;
top: 23rem;
height: 1.5625rem;
width: 1.5625rem;
background-color: #ea001d;
border-radius: 50%;
display: inline-block;
}
.closed-p {
position: relative;
top: 23rem;
color: #ea001d;
font-weight: bold;
display: inline-block;
width: 8rem;
}
/* End indicator CSS */
HTML:
<!-- Start status indicator -->
<div id="circle"></div>
<p id="message">We are open until 10 PM</p>
<script src="js/open-closed-indicator.js"></script>
<!-- End status indicator -->
You can achieve this using getDate() method for the Christmas period and use getDay() to check if it's a weekend.
Days in JS are 0 = sunday and 6 = Saturday. Refer to the comments in each line for more info.
For Christmas period dates you need to check whether it's the 11 months which is December and the date is 24 or 25th December.
To show different closed messages I am using JS ternary operator which helps to write less code and get the same results.
Live working demo.
var messageElement = document.getElementById("message");
var circleElement = document.getElementById("circle");
const refreshStatus = () => {
// Get dates/time/hours
let today = new Date(); //today date
let currentTime = today.getHours(); //get hours
let areWeekends = (today.getDay() == 6 || today.getDay() == 0) //get weekends
let santaDays = (today.getMonth() == 11 && (today.getDate() == 24 || today.getDate() == 25)) //get christmas dates
//Show available if this matches
if (currentTime >= 8 && currentTime <= 21 && !areWeekends && !santaDays) {
// Update text and add classes
messageElement.innerHTML = "We are open until 10 PM";
circleElement.className = 'open-circle';
messageElement.className = 'open-p';
} else {
//change text based on weekend / christmas or not - Using ternary operator Javascript
messageElement.innerHTML = `We are closed ${areWeekends ? ' - weekend' : santaDays ? 'Christmas' : 'until 8am'}`;
circleElement.className = 'closed-circle';
messageElement.className = 'closed-p';
}
}
// run when starting
refreshStatus();
// updates every 8 seconds
setInterval(refreshStatus, 8000);
/* Start indicator CSS */
.open-circle {
position: relative;
top: 23rem;
height: 1.5625rem;
width: 1.5625rem;
background-color: #00BF13;
border-radius: 50%;
display: inline-block;
}
.open-p {
position: relative;
top: 23rem;
color: #00BF13;
font-weight: bold;
display: inline-block;
width: 8rem;
}
.closed-circle {
position: relative;
top: 23rem;
height: 1.5625rem;
width: 1.5625rem;
background-color: #ea001d;
border-radius: 50%;
display: inline-block;
}
.closed-p {
position: relative;
top: 23rem;
color: #ea001d;
font-weight: bold;
display: inline-block;
width: 8rem;
}
/* End indicator CSS */
<!-- Start status indicator -->
<div id="circle"></div>
<p id="message">We are open until 10 PM</p>
<!-- //<script src="js/open-closed-indicator.js"></script>
-->
<!-- End status indicator -->
try this
// set your holidays
const holidays = [
{'2022-12-25' : 'christmas'},
{'2022-01-29' : 'testHoliday'},
]
const refreshStatus = () => {
// added code
let date = new Date();
let dayOfWeek = date.getDay(); // 6: saturday, 0: sunday
let today = date.getFullYear() + '-' + String(date.getMonth()+1).padStart(2, '0') + '-' + date.getDate(); // 2022-01-29
let isHoliday = holidays.filter(h => h[today]).length > 0 || dayOfWeek == 6 || dayOfWeek == 9;
//
// Set the current time
let currentDate = date.getHours();
// If the time is between 8 am and 10 pm
if (currentDate >= 8 && currentDate <= 21 && !isHoliday) {
// Update text and add classes
messageElement.innerHTML = "We are open until 10 PM";
circleElement.className = "open-circle";
messageElement.className = "open-p";
} else {
// 21 pm to 8 am
messageElement.innerHTML = "We are closed until 8 AM";
circleElement.className = "closed-circle";
messageElement.className = "closed-p";
}
};

How to add a timer on page load that stops when button is clicked?

I want to add a timer to the page where it starts on page load.
Where it goes up in milliseconds.
Then stops when the mouse is clicked on the button.
How would I create a code example of that?
That is all I am trying to do in the code.
Add a timer that starts on page load.
Goes up in milliseconds.
Then stops when the button is clicked.
I want to be able to see the numbers going up.
https://jsfiddle.net/xvkwmndq/
// Counter
var enterDate = new Date();
function secondsSinceEnter()
{
return (new Date() - enterDate) / 1000;
}
// Usage example
document.querySelector('button').onclick = function() {
var sec = secondsSinceEnter();
if (sec < 10)
this.innerText = sec + " seconds";
else
this.innerText = 'You are here like for eternity';
};
.play {
-webkit-appearance: none;
appearance: none;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
display: flex;
justify-content: center;
align-items: center;
width: 90px;
height: 90px;
border-radius: 50%;
cursor: pointer;
border: 9px solid blue;
background: transparent;
filter: drop-shadow(3px 3px 3px #000000b3);
}
<button class="play" type="button" aria-label="Open"></button>
Related to the jsfiddle in your comment:
Don't use this to access the button. Instead, just use document.querySelector:
document.querySelector('button').onclick = function() {
var sec = secondsSinceEnter();
if (sec < 10)
document.querySelector('button').innerText = sec + " seconds";
else
document.querySelector('button').innerText = 'You are here like for eternity';
}
Then, you're just adding the time when the button is clicked. Additionally, you should call it every 0ms (every 'tick') using setInterval. So that you don't have to write the function twice, you could define it as a seperate function. Finally, remove the interval when the button is clicked.
Full script:
// Interval
var interval;
// Counter
var enterDate = new Date();
function secondsSinceEnter()
{
return (new Date() - enterDate) / 1000;
}
// Event function
function evtFct()
{
var sec = secondsSinceEnter().toFixed(3);
if (sec < 10)
document.querySelector('button').innerText = sec + " seconds";
else
document.querySelector('button').innerText = 'You are here like for eternity';
}
// Add interval to keep the current time uptodate
interval = setInterval(evtFct, 0); // Call evtFct every tick
// Usage example
document.querySelector('button').onclick = function()
{
evtFct();
clearInterval(interval); // Disable interval
}

Changing the direction of content on calendar design

I'm building my own version of dynamic calendar with html css and js.
I got two issues:
Small issue: The buttons of changing to the next / previous month work as expected just after the second click.
Major issue: I can't understand how to fill last month's days on the right ("from the end") direction.
This is my code:
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var monthnames = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
var today = new Date();
document.querySelector('#monthChoose').value = (today.getMonth()+1);
document.querySelector('#yearChoose').value = today.getFullYear();
// next and previous buttons
document.querySelector('#nextM').addEventListener('click', function() { document.querySelector('#monthChoose').value = operator++; buildCalendar()});
document.querySelector('#prevM').addEventListener('click', function() {document.querySelector('#monthChoose').value = operator--; buildCalendar()});
// fill days of the week as title
for (var i=0; i < days.length; i++) {
document.querySelector('#weekdays').innerHTML += '<li><span>'+days[i]+'</span></li>';
}
var operator = document.querySelector('#monthChoose').value; // this will later on the function to restrict input value
function buildCalendar() {
if (operator > 12) {operator = 1};
if (operator < 1) {operator = 12};
document.querySelector('#days').innerHTML = ' '; // clear records
var month = document.querySelector('#monthChoose').value;
var year = document.querySelector('#yearChoose').value;
document.querySelector('#monthName').textContent = monthnames[month-1]; // display month name
function daysInMonth (month, year) { return new Date(year, month, 0).getDate(); } // constructor to get number of days in chosen month
var lastMonthDays = daysInMonth(month-1, year);
var currentMonthDays = daysInMonth(month, year);
var currentFirstDay = new Date(year, month-1 ,1);
currentFirstDayNum = new Date(currentFirstDay).getDay();
var currentLastDay = new Date(year, month ,1);
currentLastDayNum = new Date(currentLastDay).getDay();
// fill last month's days
// this cause issue: i need to change the content direction so it will fill from the opposite direction
for (var i=0; i < currentFirstDayNum; i++) {
document.querySelector('#days').innerHTML += '<li style="opacity: 0.5;">'+(lastMonthDays-i)+'</li>';
}
// fill the current month days
for (var i=0; i < currentMonthDays; i++) {
document.querySelector('#days').innerHTML += '<li>'+(i+1)+'</li>';
}
// fill the rest of the board
var liLength = document.querySelectorAll('#days > li').length;
var restOfBoard=0;
while (liLength < 42) {
restOfBoard+=1;
document.querySelector('#days').innerHTML += '<li style="opacity: 0.5;">'+restOfBoard+'</li>';
liLength++
}
}
buildCalendar();
ul {list-style-type: none; text-align: center; margin: 0; padding: 0;}
#month {padding: 30px 0; width: 100%; }
#month li input:first-child { display: none; } /* hide input that control months - will change with js*/
#monthName { display: block; }
#monthName { font-size: 2em; }
#month button {width: auto; padding: 0; font-size: 2em;}
#month #prevM {float: left;}
#month #nextM {float: right;}
#weekdays { padding: 10px 0; background-color: gray; }
#weekdays li {
display: inline-block;
color: white;
width: calc(100% / 7);
}
#days { padding: 10px 0; }
#days li {
display: inline-block;
width: calc(100% / 7);
height: calc(400px / 5);
}
<ul id="month">
<li><button id="prevM">❮</button> </li>
<li><button id="nextM">❯</button> </li>
<li id="monthName"></li>
<li>
<input type="number" id="monthChoose" onchange="buildCalendar()" />
<input type="number" id="yearChoose" onchange="buildCalendar()"/>
</li>
</ul>
<ul id="weekdays"></ul>
<ul id="days"></ul>
Note: will glad to hear about things i could do better with this code...
EDIT:
The expected result for the second issue is the lest days of last month. If we take October 2019: the first day is Tuesday so on this week Monday should be the 30th and Sunday the 29th. Can't understand how to fill those days in this order dynamically.
So i finally managed to solve the second problem: Gave the lastMonthDays a unique class, sort it by it content, append the sorting elements, and then proceed with the rest of code.
For this i modified this script for my needs.
Thanks everybody.
The first problem is quite easy to solve by changing
document.querySelector('#monthChoose').value = operator++;
to
document.querySelector('#monthChoose').value = ++operator;
and changing
document.querySelector('#monthChoose').value = operator--;
to
document.querySelector('#monthChoose').value = --operator;
Putting ++ after operator means you don't increase the value of operator until afer you copy its value to the "monthChoose" element, where as putting it beforehand ensures you change its value first. And of course you later use the "monthChoose" element's value to determine the actual month to be displayed.
N.B. It's unclear why you actually need two values here at all - that is just a recipe for confusion. Since operator is global, you could just use that all the way through. Alternatively you could use the "monthChoose" element to maintain state if you want to reduce your use of global variables (which generally, you should).
Here's a demo:
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var monthnames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var today = new Date();
document.querySelector('#monthChoose').value = (today.getMonth() + 1);
document.querySelector('#yearChoose').value = today.getFullYear();
// next and previous buttons
document.querySelector('#nextM').addEventListener('click', function() {
document.querySelector('#monthChoose').value = ++operator;
buildCalendar()
});
document.querySelector('#prevM').addEventListener('click', function() {
document.querySelector('#monthChoose').value = --operator;
buildCalendar()
});
// fill days of the week as title
for (var i = 0; i < days.length; i++) {
document.querySelector('#weekdays').innerHTML += '<li><span>' + days[i] + '</span></li>';
}
var operator = document.querySelector('#monthChoose').value; // this will later on the function to restrict input value
function buildCalendar() {
if (operator > 12) {
operator = 1
};
if (operator < 1) {
operator = 12
};
document.querySelector('#days').innerHTML = ' '; // clear records
var month = document.querySelector('#monthChoose').value;
var year = document.querySelector('#yearChoose').value;
document.querySelector('#monthName').textContent = monthnames[month - 1]; // display month name
function daysInMonth(month, year) {
return new Date(year, month, 0).getDate();
} // constructor to get number of days in chosen month
var lastMonthDays = daysInMonth(month - 1, year);
var currentMonthDays = daysInMonth(month, year);
var currentFirstDay = new Date(year, month - 1, 1);
currentFirstDayNum = new Date(currentFirstDay).getDay();
var currentLastDay = new Date(year, month, 1);
currentLastDayNum = new Date(currentLastDay).getDay();
// fill last month's days
// this cause issue: i need to change the content direction so it will fill from the opposite direction
for (var i = 0; i < currentFirstDayNum; i++) {
document.querySelector('#days').innerHTML += '<li style="opacity: 0.5;">' + (lastMonthDays - i) + '</li>';
}
// fill the current month days
for (var i = 0; i < currentMonthDays; i++) {
document.querySelector('#days').innerHTML += '<li>' + (i + 1) + '</li>';
}
// fill the rest of the board
var liLength = document.querySelectorAll('#days > li').length;
var restOfBoard = 0;
while (liLength < 42) {
restOfBoard += 1;
document.querySelector('#days').innerHTML += '<li style="opacity: 0.5;">' + restOfBoard + '</li>';
liLength++
}
}
buildCalendar();
ul {
list-style-type: none;
text-align: center;
margin: 0;
padding: 0;
}
#month {
padding: 30px 0;
width: 100%;
}
#month li input:first-child {
display: none;
}
/* hide input that control months - will change with js*/
#monthName {
display: block;
}
#monthName {
font-size: 2em;
}
#month button {
width: auto;
padding: 0;
font-size: 2em;
}
#month #prevM {
float: left;
}
#month #nextM {
float: right;
}
#weekdays {
padding: 10px 0;
background-color: gray;
}
#weekdays li {
display: inline-block;
color: white;
width: calc(100% / 7);
}
#days {
padding: 10px 0;
}
#days li {
display: inline-block;
width: calc(100% / 7);
height: calc(400px / 5);
}
<ul id="month">
<li><button id="prevM">❮</button> </li>
<li><button id="nextM">❯</button> </li>
<li id="monthName"></li>
<li>
<input type="number" id="monthChoose" onchange="buildCalendar()" />
<input type="number" id="yearChoose" onchange="buildCalendar()" />
</li>
</ul>
<ul id="weekdays"></ul>
<ul id="days"></ul>
I'm afraid I don't understand precisely what you mean by your second problem. Perhaps you can give a clearer description / diagram showing what you want to happen and then I can update this answer?

Reset first countdown after the second countdown

Im working on a simple countdown that displays a modal when it is zero, then on that modal there is another countdown, it will close when on zero.
what I want is reset the first countdown again and do the same process.
How can I achieve that?
hope you understand me.
Thanks.
SAMPLE CODE
//declare start time
var timer2 = "00 : 00 : 10";
// timer2 = timer2.replace(/秒|_/g,'')
//intercal for seconds
var interval = setInterval(function() {
//timer will be [hour, minute, second]
var timer = timer2.split(':');
var hour = parseInt(timer[0], 10);
var minutes = parseInt(timer[1], 10);
var seconds = parseInt(timer[2], 10);
//reduce second by one
--seconds;
//calculate new minute and hours
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0) {
minutes = 00;
seconds = 00;
clearInterval(interval);
$('#informationModal').fadeIn();
var timeleft = 4;
var downloadTimer = setInterval(function(){
timeleft--;
$('.sec').text(timeleft);
if(timeleft == 0){
clearInterval(downloadTimer);
$('#informationModal').fadeOut();
minutes = 00;
seconds = 10;
}
},1000);
}
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
minutes = (minutes < 0) ? 59 : minutes;
minutes = (minutes < 10) ? '0' + minutes : minutes;
hour = (hour < 0) ? 59 : hour;
hour = (hour < 10) ? '0' + hour : hour;
timer2 = hour + ':' + minutes + ':' + seconds;
$('#countdown').html(timer2);
}, 1000);
Easiest way would be to wrap everything into a function, and call that function again when fadeOut of modal completes.
$('#informationModal').fadeOut(400, startTimer);
function startTimer() {
//declare start time
var timer2 = "00 : 00 : 10";
// timer2 = timer2.replace(/秒|_/g,'')
//intercal for seconds
var interval = setInterval(function() {
//timer will be [hour, minute, second]
var timer = timer2.split(':');
var hour = parseInt(timer[0], 10);
var minutes = parseInt(timer[1], 10);
var seconds = parseInt(timer[2], 10);
//reduce second by one
--seconds;
//calculate new minute and hours
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0) {
minutes = 00;
seconds = 00;
clearInterval(interval);
$('#informationModal').fadeIn();
var timeleft = 4;
var downloadTimer = setInterval(function() {
timeleft--;
$('.sec').text(timeleft);
if (timeleft == 0) {
clearInterval(downloadTimer);
$('#informationModal').fadeOut(400, startTimer);
minutes = 00;
seconds = 10;
}
}, 1000);
}
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
minutes = (minutes < 0) ? 59 : minutes;
minutes = (minutes < 10) ? '0' + minutes : minutes;
hour = (hour < 0) ? 59 : hour;
hour = (hour < 10) ? '0' + hour : hour;
timer2 = hour + ':' + minutes + ':' + seconds;
$('#countdown').html(timer2);
}, 1000);
}
startTimer();
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="countdown"></div>
<!-- The Modal -->
<div id="informationModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<p>Some text in the Modal..<span class="sec"></span></p>
</div>
</div>
This is to give you an idea how you could solve it with scoping your code in a function and then call that function over and over again.
var timer2 = "00 : 00 : 5";
var hour = 0;
var minutes = 0;
var seconds = 0;
var setupTime = function(time){
let timer = time.split(':');
hour = parseInt(timer[0], 10);
minutes = parseInt(timer[1], 10);
seconds = parseInt(timer[2], 10);
}
setupTime(timer2);
var myFunction = function(){
var interval = setInterval(function() {
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0 && seconds < 0) {
clearInterval(interval);
$('#informationModal').fadeIn();
var timeleft = 4;
var downloadTimer = setInterval(function(){
timeleft--;
$('.sec').text(timeleft);
if(timeleft == 0){
clearInterval(downloadTimer);
$('#informationModal').fadeOut();
// resetTimer and call myFunction to start again
setupTime(timer2);
myFunction();
}
},1000);
} else {
$('#countdown').html(seconds);
}
}, 1000);
};
myFunction();
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="countdown"></div>
<!-- The Modal -->
<div id="informationModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<p>Some text in the Modal..<span class="sec"></span></p>
</div>
</div>
You need to be careful with variables if you change them from integers to strings. That's why the time is not visible as 00:00:00 but you will figure out how to solve that.
Side note: If you ask a question. Please always check your indents and fix them as long as you need to provide "clean" code. As it is no fun to fix indents to answer a question.

Hours of Operation Status

I made this little object that lets you know if a place is open based on two variables. However I would like to make this even better, because I am not very good at javascript I want to know what's best practice. How would I update open/close status in real-time for the user that gets there a minute before they close or open.
CodePen Source
html
<h1 class="status"></h1>
<h2 class="hours"></h2>
css
body {
color: white;
text-align: center;
font-size: 2em;
}
.open { background-color: #00a638; }
.closed { background-color: black; }
js
// variables
var open = "7:00";
var close = "5:00";
// setup miliary time
var mClose = close.replace(/:/g,'') + 1200;
var mOpen = open.replace(/:/g,'');
if (mOpen < 1000) {
mOpen = "0" + mOpen;
}
// setup hours
var now = new Date();
var hour = now.getHours();
if (hour >= 10) { mHour = hour;
} else { mHour = "0" + hour; }
// setup minutes
var minute = now.getMinutes();
if (minute < 10) {
minute = "0" + minute;
}
var time = "" + mHour + minute;
console.log("Time is " + time);
// open/close status
if ((time >= mOpen) && (time < mClose)) {
$("body").addClass("open");
$(".status").html("Yes, We're Open");
} else {
$("body").addClass("closed");
$(".status").html("Sorry We're Closed");
}
// display hours
$(".hours").html(open + " to " + close);

Categories