To change a css style depending on time of day (javascript) - javascript

im trying to write a little .js file to change a css style from display:block to display:none depending on the time of day, 08.30 to 17.00 display block and 17.00 to 08.30 display none.
Here's what i have so far:
<script language="JavaScript">
day=new Date() //..get the date
x=day.getHours() //..get the hour
if(x>=8.30 && x<17) {
document.write('<style type="text/css">#live{display:block}"></style>')
} else
if(x>=17 && x<8.30) {
document.write('<style type="text/css">#live{display:none}"></style>')
};
</script>
Do think this is good js plus not sure if using 8.30 would work plus not sure if the last ";" is needed.
Any help on this would be great thanks.
Im now trying this code but does not work
<script type="text/javascript">
$(document).ready ( function (){
var dateObj = new Date();
var hour = dateObj.getHours() * 100 + dateObj.getMinutes();
if (hour >= 1600 && hour <= 1800) {
document.getElementById('live').style.display = "none";
}
});
</script>

Date().getHours() returns an integer. For your code to work you'd have to do something like this:
var dateObj = new Date();
var hour = dateObj.getHours() * 100 + dateObj.getMinutes();
if (hour >= 830 && hour <= 1700) {
document.getElementById('your_el').style.display = "none";
}
Note that you should only use this code when the DOM is ready for manipulation.
Although, is this really what you want? JavaScript's Date gets its date and time information from the users' clock. You would probably be better off handling this on the server.

getHours() returns a whole number (0 to 23). For 8:30, you will
need to check getHours() and getMinutes() accordingly.
The last semicolon does not need to be there.

getHours() only gets you the hours number, you need to get the minutes as well
try with
x=day.getHours()+ (day.getMinutes()/100);
about the ; it is not neccessary after an if, but it's good practice to put it at the end of each code line (that would be every other line)

Related

Highlight text at specific time of day

I need to highlight text at a specific time.
<style>
.highlight {
background-color:#FFFF00;
}
</style>
<span class="timer">Hello World</span>
<script>
var date = new Date();
var minute = date.getMinutes();
var hour = date.getHours();
if(
(hour >= 9 && minute >= 59) &&
(hour <= 10 && minute <= 59)
){
$('timer').addClass('highlight');
}
</script>
In the above example, it should highlight "Hello World" between 10:00 and 11:00.
This isn't working - any thoughts?
Like A. Damond said your if statement is only true if your time is either 9:59 or 10:59.
I would change your if statement to:
var date = new Date();
var minute = date.getMinutes();
var hour = date.getHours();
if ((hour === 10)) {
$('.timer').addClass('highlight');
}
.highlight {
background-color: #FFFF00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="timer">Hello World</span>
Also you have to add the right selector in your jQuery addClass call.
$('.timer') not $('timer').
EDIT I've updated the if clause
Your if statement is equivalent to doing the same thing without parentheses. So you're checking to see if the hour is both greater than or equal to 9 and less than or equal to 10 (which will only be true if the hour is either 9 or 10) and also if the minute is both greater than or equal to 59 and less than or equal to 59 (which will only happen if the minute is exactly 59). So your if statement is only going to return true if your time is either 9:59 or 10:59.
Why not just use if (hour === 10)?
it doesn't work because in the jQuery selector you have to put a 'dot'.
$('.timer').addClass('highlight');
when you want select an id, just put
$('#timer').addClass('highlight');
As #Damon has suggested, it's simpler if you just check only the hour
(=== 10 || (=== 11 && minute === 00)) // this will include also the 11:00
Of course, if final user opens the page (at 10) and he/she never updates/reloads, the background will be always visible, or the opposite, if he opens the page at 9.
To do a job well done and working properly, you have to introduce a clock on the page and this can be a good example:
http://www.tristanwaddington.com/2010/08/javascript-clock/

setInterval and 12 hour clock in javascript

I want to write a script that changes the hour displayed inside a <span> every second, starting from 8AM, and which keeps repeating like a 12 hours clock (11AM, 12PM, ..., 11PM, 12AM, 1AM, ...).
The image will change at 8AM and 8PM. At 8PM, the image will change to a sleeping face, and at 8AM the image will change back to a smile face. However, that is not a problem.
The problems are:
When I set var hour = Number(document.getElementById("time").textContent); then setInterval repeats the time without any problem. However, when I set var hour = 8 instead, and keep same code, then setInterval repeats only once. Can you let me know why it is like that and how to fix it with var hour = 8?
When the hour is repeatedly increased, I cannot make it smart to change back to AM when it reaches to 12 after passing noon (12PM). For example, the code works fine from 8AM to 11PM but when it reaches to 12, the PM does not change to AM. Can you show me how to fix it?
Lastly when I change var period = "AM" instead of using DOM getElementByID like above and keep same code, then it runs to 1PM and then changes to 2AM and never changes to PM again. Can you explain to me why it happens?
If you do not know what I am talking about, you can run my code and to understand more.
Here is the HTML:
<h2>Life goes on!</h2>
<p>The current time is : <span id = "time">8</span> <span id = "period"> AM</span></p>
<img id = "emoticon" src = "smile.gif" alt = "awake">
And here is my JavaScript code:
setInterval(function () {
var hour = Number(document.getElementById("time").textContent);
hour++;
var period = document.getElementById("period").textContent;
if (hour >= 12) {
hour = hour - 12;
period = "PM";
}
if (hour == 0) {
hour = 12;
}
document.getElementById("time").textContent = hour;
document.getElementById("period").textContent = period;
if (hour == 8 && period == "PM") {
document.getElementById("emoticon").src = "sleep.gif";
document.getElementById("emoticon").alt = "sleep";
} else if (hour == 8 && period == "AM") {
document.getElementById("emoticon").src = "smile.gif";
document.getElementById("emotion").alt = "awake";
}
}, 1000);
Let me explain the problems of your code, using the same three points you made:
Your problem about var hour = 8; is that, if you set the hour inside the setInterval callback, your hour will be set to 8 at any second. Therefore, your setInterval doesn't work only once, but it gets run infinite times setting the time always to 9. To avoid this, you can move the variable outside and make it global, setting it to 8 before starting the setInterval.
To change "PM" back to "AM" when it reaches 12PM, just add an if statement (or, better, a ternary operator, like I did in the snippet below) to check if the period is either "PM" or "AM", and behave consequently. Also, be careful with the check: if you check directly on .textContent be sure that the text inside the <span> doesn't have any trailing space: use .trim() to remove extra spaces at the beginning and at the end of the string.
This is the same problem of point 1: you should make the variable period global, and then start the setInterval.
The logic of the following script is simple:
Increase the hour by 1
If the new hour equals 12, then switch to "PM" or back to "PM"
If the new hour is greater than 12, then reset it to 1
Display hour and period
Change from smile.gif to sleep.gif when it's 8PM, and vice versa when it's 8AM.
I also made some little changes to make code easier and faster to read. Here is a working code snippet:
var hour = 8,
period = "AM";
setInterval(function() {
if (++hour >= 12) {
if (hour > 12) hour = 1;
else period = (period == "PM") ? "AM" : "PM";
}
document.getElementById("time").textContent = hour;
document.getElementById("period").textContent = period;
if (hour == 8 && period == "PM") {
document.getElementById("emoticon").src = "sleep.gif";
document.getElementById("emoticon").alt = "sleep";
} else if (hour == 8 && period == "AM") {
document.getElementById("emoticon").src = "smile.gif";
document.getElementById("emotion").alt = "awake";
}
}, 1000);
<h2>Life goes on!</h2>
<p>The current time is: <span id="time">8</span> <span id="period">AM</span></p>
<img id="emoticon" src="smile.gif" alt="awake">
Here it is, it works fine now, give it a try clicking on "Run code snippet".

Best Way to detect midnight and reset data

I've been developing a web application Dashboard and I was wondering how to detect that is midnight in order to reset some arrays that contains datas from the previous day using jquery or momentjs.
Use moment().format("h:mm:ss") that returns time in a h:mm:ss format.
var midnight = "0:00:00";
var now = null;
setInterval(function () {
now = moment().format("H:mm:ss");
if (now === midnight) {
alert("Hi");
}
$("#time").text(now);
}, 1000);
JSFIDDLE
A better way would be to compute the seconds until midnight. This is very simple and human readable using MomentJS:
// returns the number of seconds until next midnight
moment("24:00:00", "hh:mm:ss").diff(moment(), 'seconds');
So, just do:
setTimeout(
midnightTask,
moment("24:00:00", "hh:mm:ss").diff(moment(), 'seconds')
);
function midnightTask() {
/* do something */
}
JSFIDDLE
There's only really two ways to accomplish this
poll every x seconds and see whether we're within x seconds of midnight
Calculate the time between now and midnight, and sleep for that amount of time before executing
(1) has been demonstrated in other answers, here's (2).
The first thing to do is calculate the number of milliseconds until midnight then use that as a parameter to javascripts setTimeout.
setTimeout(function(){
// whatever you want to do at midnight
}, msToMidnight);
After you've finished your work in that function, you might want to recaculate the time until next midnight and repeat the process.
So I think you're going about this the wrong way. What you're looking for isn't when it's midnight, you just want to know when the day has changed, which is a much simpler task.
The first thing I'm going to say is avoid using timers at all costs. They're not worth it. The performance hit and extra CPU time you take from running the same function >3600 times a day is ridiculous, especially when it's running on someone else's computer. You don't know how much it can handle, so assume it can't handle much at all. Go easy on your users.
I would suggest listening to a user input event, assuming that this is something you would have on a regular computer, and not something like this, where there is no user input.
If user input events are something you could rely on, I would do this..
var today = new Date(), lastUpdate;
window.addEventListener( "mousemove", function () {
var time = new Date();
// If we haven't checked yet, or if it's been more than 30 seconds since the last check
if ( !lastUpdate || ( time.getTime() - lastUpdate.getTime() ) > 30000 ) {
// Set the last time we checked, and then check if the date has changed.
lastUpdate = time
if ( time.getDate() !== today.getDate() ) {
// If the date has changed, set the date to the new date, and refresh stuff.
today = time
this_is_where_you_would_reset_stuff()
}
}
} )
If you absolutely need to use a timer, then I would do this..
function init() {
var today = new Date();
var midnight = new Date();
midnight.setDate( today.getDate() + 1 )
midnight.setHours( 0 )
midnight.setMinutes( 0 )
setTimeout( function () {
// If the date has changed, set the date to the new date, and refresh stuff.
today = time
this_is_where_you_would_reset_stuff()
init()
}, midnight.getTime() - today.getTime() )
}
init()
Keep in mind that the second way is likely to be far less reliable.
Create a date at midnight this morning, add 86400 seconds, and set a timeout for then:
new Date(Date.parse((new Date()).toString().replace(/\d\d:\d\d:\d\d/,'00:00:00')) + 86400 * 1000)
Here's how you'd use it:
var delay_to_midnight = Date.parse((new Date()).toString().replace(/\d\d:\d\d:\d\d/,'00:00:00')) + 86400 * 1000 - Date.now()
var timeoutid = window.setTimeout(function() { alert("It's midnight!"); }, delay_to_midnight);
I would try:
window.setInterval(resetAtMidnight, 1000*5) // every five seconds
function resetAtMidnight() {
var now = new Date();
if(now.getHours() < 1
&& now.getMinutes() < 1
&& now.getSeconds() < 5 ) {
redrawPage();
}
};

Javascript between Two Times

I'm currently trying to create a JavaScript which will display on our website when our shop is open, and when it is closed.
I basically want to create an if statement between two times, these being 8:30 and 5:30.
I'm currently doing the following, although it won't work as I effectively have two lots of 'minutes' defined which cancel each other out.
<script type="text/javascript">
var Digital=new Date();
var day=Digital.getDay();
var hours=Digital.getHours();
var minutes=Digital.getMinutes();
// Monday - Open //
if (day==1 && hours>=8 && minutes>=30 && day==1 && hours<=17 && minutes<=30)
document.write('Open today until 5:30pm');
</script>
Can anyone suggest a way of achieving what I am trying to do?
How about this:
if(day == 1 && hours*60+minutes >= 510 && hours*60+minutes <= 1050) {
// do stuff
}
With 8 * 60 + 30 = 510 and 17 * 60 + 30 = 1050.
One thing to note here is
new Date()
gets the local time from the client's clock. If the client's clock is set at a different time zone you might not get the result you are hoping for.
I would suggest getting the client's timezone as well and converting that to your desired timezone adding/subtracting any offset, start with something like
var clientTime = new Date();
var clientTimeZone = clientTime.getTimezoneOffset();
//getTimezoneOffset returns the time-zone offset in minutes between the current locale and UTC.

PHP, javascript, jquery, setting hour only

I have created a small function that i need on my site successfully in php. But i now realise i actually need this in javascript or jquery as PHP will only excute this code on load.. i need this function to work with onchange on a select. The code below is my function.. Can anyone point out where i start to convert this into js/jquery like code:
function setTrnTime ($hr, $journeyTime){
date_default_timezone_set('GMT');
//convert current hour to time format hour
$currentHour = (date("H", mktime($hr)));
// Journey time in hours
$journey = $journeyTime
$journey = $journey/60; // Get hours
$journey = ceil($journey); // Round off to next hour i.e. 3 hours 20mins is now 4 hours
// New Hours
$NewHour = (date("H", mktime($journey)));
$Newhour = $NewHour*60*60; // convert to seconds
// Final hour is Current Hour - JourneyTime (Hours)
$trnHour = (date('H', mktime($currentHour-$NewHour)));
return $trnHour;
}
With the code above, if i pass two values 06, 60: that would mean my answer would be 05. e.g. 06 is 6am. 60 is 60mins.. so 6am - 60mins = 5am.
You can do the same in javascript using the Date object, see info here
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
EDITED: Added some code, also not even using the Date object.
But do you need something that complex, doesn't the following do what you are after with less steps.
http://jsfiddle.net/WWTDc/
If hr is a Date object, then it's very simple. Otherwise you can create a Date object and set its hour:
//! \param[in] hr Date object or hour (0--23)
//! \param[in] journeyTime journey time in minutes.
function setTrnTime(hr,journeyTime){
var end;
if(typeof(hr) === 'number'){
end = new Date();
end.setHours(hr);
}
else
end = hr;
return (new Date(end - journeyTime*60*1000)).getHours();
}
This will return the hour (demonstration).
See here for information about Date object in JavaScript.

Categories

Resources