Reputation: 85
I'm working on a website that contains many elements that change based on the time of day. I would like to have an image change based on the time of day, one image for a day period, and one for night, so:
Day image = 8:30–00:00
Night image = 00:00–8:30
I came across this example on Stackoverflow, but I'm not sure if this is accurate to my browser time (the image change should be based on my time and not the users).
This is the example:
$( document ).ready(function() {
SetImage();
window.setInterval(SetImage,1000);
});
function SetImage(){
var nowdate = new Date() ;
var waketime = new Date();
waketime.setHours(6);
waketime.setMinutes(30);
var bedtime = new Date();
bedtime.setHours(18);
bedtime.setMinutes(30);
if(waketime < nowdate && nowdate < bedtime){
$('#day').show();
$('#night').hide();
}else{
$('#night').show();
$('#day').hide();
}
}
<img id="night" src="http://1.bp.blogspot.com/_7-b4ZWNPaD8/TThuPK0cvUI/AAAAAAAAAAQ/jCqRshKkJd4/s1600/night-scene.jpg">
<img id="day" src="http://media1.santabanta.com/full1/Events/Independence%20Day/independence-day-67a.jpg">
Any ideas? Any help would be fantastic. Thank you :-)
Upvotes: 1
Views: 5323
Reputation: 746
Client Time :
If you are talking about the client time, that's good. But I recommand to change the interval used to 10 min or more.
Server Time:
But If you are talking about the server time, the response will be no. You have to pass the time of your server by a backend code like php,java,node... Or, you can use time given api, like this :
<script type="text/javascript">
function myCallback(json) {
alert(new Date(json.dateString));
}
</script>
<script type="text/javascript" src="http://timeapi.org/utc/after+one+hour.json?callback=myCallback"></script>
This work only if you use JSONP. What we do is we request this url that contains the time of your server (in Amsterdam): http://www.timeapi.org/utc/after+one+hour
Upvotes: 0
Reputation: 87313
Server side you check time and based on it, you add either night or day to the body (as class or data attribute)
Additionally, you can run your script and update it if a user doesn't reload.
window.setInterval(SetImage,5000); /* set this to at least 10 min */
function SetImage(){
var nowdate = new Date();
var waketime = new Date();
waketime.setHours(6);
waketime.setMinutes(30);
var bedtime = new Date();
bedtime.setHours(18);
bedtime.setMinutes(30);
if(waketime < nowdate && nowdate < bedtime) {
document.body.setAttribute('data-daytime','');
}else{
document.body.setAttribute('data-nighttime','');
}
}
.toggletime {
padding: 10px;
background: #eee;
color: #333;
}
body[data-nighttime] .toggletime {
padding: 10px;
background: #333;
color: #eee;
}
<body data-daytime>
<div class="toggletime">
Hey there
</div>
</body>
Upvotes: 1