Time & Date dependent Page Content - javascript

I'm trying to get a video feed to only display on Thursdays between 7PM and 8PM because that's when the live feed is playing. For reasons I'll not go into, I'm not allowed to have it up at any other time. Since I'm new to JavaScript I'm sure I'm doing something wrong, but from what I've been able to learn this is what I've got.
var hour = getHours()
var day = getDay()
document.onload=function timechange() {
if day==4 && hour>19 && hour<21
document.getElementById(livefeed).innerHTML =
"Text one"
else
document.getElementById(livefeed).innerHTML =
"Text two"
}
This is example text obviously but the majority of the content will change on the page. Do I have to add some sort of function in my HTML page to make this work?

For the simple version, that's almost that. getDay() and getHours() are defined on the Date class:
function shouldShowVideo() {
var currentDate = new Date(),
currentDay = currentDate.getDay(),
currentHour = currentDate.getHours();
return (currentDay == 4 && currentHour > 19 && currentHour < 20);
}
if (shouldShowVideo()) {
// do something
} else {
// do something else
}
There is one big problem with this approach though. Because you do it in JS, the video will be loaded on your page, no matter what (so people could potentially get the link to it).
Also, because you are executing your JS after the onload event fired, there could be a few seconds where the video will be displayed. What you can do to improve this is run this code on DOM Ready event instead (here is the jQuery helper: http://api.jquery.com/ready/).
Your best option would still be to move this logic on the server. That way, you don't have to worry about all this: no JS involved.

Related

How to check H2 tag with a date against 1 week in the future on a simple web page

Let's say I have the following HTML page;
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
</head>
<body>
<h2 id='invoiceDueDate'>17/08/2018</h2>
<h2 id='paymentStatus'>Yet To pay</h2>
</body>
</html>
I need to check the h2 for the due date, check the payment status for whever its paid or not and if the current day is one week past the invoiceDueDate and is still unpaid then the page needs to display Payment Over Due
It may be obvious but if it is paid then do nothing.
It doesn't necessarily have to use moment.js but it has to use this date format: dd/mm/yyyy
Here is the javascript I have used to try to get it working:
let dueDate = document.getElementById('invoiceDueDate').innerHTML;
console.log(dueDate)
// this get the the due date from the html and I have used console.log to confirm it works
let invoiceStatus = document.getElementById('paymentStatus').innerHTML;
console.log(invoiceStatus)
// this get the theinvoiceStatus from the html and it works
const overDue = moment().add(7, 'days').format('L');
console.log(overDue)
// get the current date and adds 7 days and it works
// todays date isnt the due date so adding 7 on to it doesn't work
if(invoiceStatus.innerHTML === 'Yet To pay'){
if(dueDate >= overDue){
invoiceStatus.innerHTML = "Overdue";
console.log('overdue');
}else{
invoiceStatus.innerHTML = "Un-paid";
console.log('not yet paid');
}
} else {
// do nothing
}
// compares the dueDate to overDue then print it out to the page
The problem with this javascript is it checks the current date then adds 7 days then print the result rather than adding 7 days to the due day THEN printing the result. This is the problem I'm struggling with.
I hope this makes sense.
Edit:
Also is there anyway to do soemthing like this
if(dueDate >= (dueDate + 7 days)){
invoiceStatus.innerHTML = "Overdue";
}
I've made changes and added it to codepen:
https://codepen.io/anon/pen/rZaLvb?editors=1010
It appears that your logic is requiring these to be completely identical. You might want to check instead to see if overdue >= dueDate -- otherwise, it will only count things that are precisely overdue, and not n days overdue.
Also, at some points you're trying to hit the innerHTML of an item's innerHTML.
The changes I would make here:
1) Change:
let invoiceStatus = document.getElementById('paymentStatus').innerHTML;
console.log(invoiceStatus);
To:
let invoiceStatus = document.getElementById('paymentStatus');
console.log(invoiceStatus.innerHTML);
2) Change:
if(dueDate === overDue){
To:
if(overDue >= dueDate){

Using Javascript I want to be able to run a particular task at a certain time

I know javascript is not the best way to go about this. I know that I would have to have the browser up and always running. I would normally do something with Python. This was a specific requests of me and i'm not very proficient with javascript. That being said.
I want the user to be able to set a time using inputs. Once these inputs have been set I want the browser to check for the time specified. Once the time occurs I want it to execute a command.
Her is what I have so far:
<html>
<body>
<p>Enter Time to start dashboard</p>
<p>Hour</p>
<input id="strthour">
<p>Minute</p>
<input id="strtmin">
<button onclick="setTime()">Submit</button>
<script>
var hr = 06; //default time of 6am to run
var mn = 00;
function setTime() {
hr = strthour.value;
mn = strtmin.value;
}
window.setInterval(function(){ // Set interval for checking
alert(hr+mn);
var date = new Date(); // Create a Date object to find out what time it is
if(date.getHours() === hr && date.getMinutes() === mn && date.getSeconds() === 0){ // Check the time
alert("it worked")
}
}, 5000); // Repeat every 60000 milliseconds (1 minute)
</script>
</body>
</html>
I am able to change the global variables, but I am unable to get window.setInterval to recognize the changes. Any advice?
Here is a link to a JSFiddle I made.
There are several issues with your code, which various people have pointed out.
Walker Randolph Smith correctly notes that date.GetHours() and date.getMinutes() will both return numbers, while the values returned from strthour.value and strtmin.value will be strings. When JavaScript compares these two, it will always evaluate to false. To fix this, try running the user input through parseInt, as in hr = parseInt(strthour.value, 10);. The 10 is important because it tells parseInt to create a number of base 10 (you don't need to know what that means, just make sure to include the 10).
Your need for the seconds to match is probably unnecessary, and does not match up with the interval you chose. TheMintyMate made this correction in their code snippet by simply removing the comparison for seconds. If you really need to make sure the seconds match up perfectly, pick an interval of less than 1000 milliseconds, so you know it is going to check at least once every second, guaranteeing that you will run the check on that 0th second of the desired time.
You could run into some trouble with single digit minutes if you try to compare them as strings, rather than converting to numbers as recommended in point 1. The .getMinutes() method will return a single digit 0 for a time like 6:00, while your example is implicitly prompting the user to enter in two digits for that same time. Again, you can avoid this issue entirely by using parseInt as recommended in point #1.
I do have to throw in a plug for using Cron jobs for running tasks on a known schedule like this. I know you said the user requested JS in this case, so they may not apply for this specific situation. Since you didn't mention Cron jobs though, I have to include them here to make sure you and future readers are aware of them, because they are designed for exactly this situation of running a task on an automated schedule.
Good luck!
You are not correctly referring to the inputs, and you also have a syntax error with your alert. Below is my suggested fix (working):
<p>Enter Time to start dashboard</p>
<p>Hour</p>
<input id="strthour">
<p>Minute</p>
<input id="strtmin">
<button onclick="setTime()">Submit</button>
<script>
var hr = 0;
var mn = 0;
function setTime() {
hr = parseInt(document.getElementById("strthour").value);
mn = parseInt(document.getElementById("strtmin").value);
console.log("set time: "+hr+":"+mn);
}
setInterval(function(){
var date = new Date();
if(date.getHours() == hr && date.getMinutes() == mn){ // using == not ===
alert("it worked");
}
}, 10000);
</script>
Note: You should also parseInt() the values to ensure they are valid numbers.
if(date.getHours() === hr && date.getMinutes() === mn && date.getSeconds() === 0){ // Check the time
alert("it worked")
}
This will compare a string to an int and always be false.
either perform parseInt(date.getHours()) or use ==
It's not because setInterval doesn't recognize the change, you actually don't modify the values.
If you open the javascript console on jsfiddle page you'll see "Uncaught ReferenceError: setTime is not defined".
It will work if you define you setTime like this:
window.setTime = function() {
hr = strthour.value;
mn = strtmin.value;
}
This is because JSFiddle doesn't run your code directly, but wraps into
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
... // you code here }
}//]]>
Here is a modified JSFiddle which just "it worked" for me.
Update - some notes, as mentioned in other answers:
The use of '===' is also an issue, hr/mn are strings, so you need '==' or convert hr/mn to integers
Expression like strthour.value in setTime works in JSFiddle. I am not really sure why, but it works. In the "real world" it should be something like document.getElementById("strthour").value
Update 2 - why does strthour.value work (vs document.getElementById("strthour").value)?
This was actually a surprise for me, but it looks like all major browsers put all elements with id into window object. More than that, it is actually a part of the HTML standard (although it is not recommended to use this feature):
6.2.4 Named access on the Window object
window[name]
Returns the indicated element or collection of elements.
As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the Web platform, for example. Instead of this, use document.getElementById() or document.querySelector().
References:
HTML 5.1 - 6.2.4 Named access on the Window object
Do DOM tree elements with ids become global variables?
Why don't we just use element IDs as identifiers in JavaScript?
I think you should use ">=" operator, because you don't know if it's gonna be EXACTLY that time.

Meteor.js: time-based server calls?

We're trying to make an application that pairs users in a database every Wednesday and Friday. How is done in Meteor?
So in the server code I was thinking of putting this in a timedserver.js file
boolean hasMatched = false;
boolean isWednesday = false;
while(true){
if (day != Wednesday) isWednesday = false;
if (day == Wednesday){
matchUsers()
Wednesday = true;
}
setTimeOut(5 HOURS)
}
Is this how it should be approached? I'm not sure how to have continually running server code. Where do we put this code?
I would propose to use Meteor.setInterval() instead of using an infinite while-loop, and why not using an interval of 24 hours instead of 5?
Then you can check the weekday of the current date, e.g. with moment.js, and if it's wednesday or friday, run your code, at best asynchronously and non-blocking the interval.
I probably wouldn't use a while loop for something like this.
One package comes to mind though: synced-cron. It looks like it uses "Parsers" and there is quite a bit flexibility there.
Something like this would probably work:
SyncedCron.add({
name: 'Crunch some important numbers for the marketing department',
schedule: function(parser) {
// parser is a later.parse object
return parser.text('every Wednesday');
},
job: function() {
var matchedUsers = matchUsers();
return matchedUsers;
}
});
I've never uses this package, but I believe this code would fire every Wednesday.
May be using cron job will be better solution?

HTML passing parameters to javascript function that then does a date compare and then javascript returning a result to be displayed in html

I am having problems figuring out how to do a date compare in Javascript, and how to pass and receive varialbes to and from Javascript Function and Html.
I have 4 term dates (workshop start and end dates for each term). I will send one set of dates at a time to the javascript function, and then I want the Javascript to check if today's date falls within the range of that workshop. Then the javascript should return a value like "workshop finished", "workshop in progress", "workshop to come" (depending on wheiter todays date is before, during, or after that specific date range). I'll call the function 4 different times - each with a different range of dates.
So for example, If the first set of dates are: 6th February till 13th March 2014, then how would I call the javascript function? This is what I have so far:
In the html - at the point where I want the status to be displayed, I tried this:
<script language="JavaScript" type="text/javascript">
<!--//
document.write(displayStatus(02062014, 03132014));
//-->
</script>
<noscript></noscript>
I know that the above date formating is probably wrong that I am trying to send to the function, but I am not sure what format is needed to do a date compare. (Note: the empty noscript tags are because if scripting is turned off, I don't want anything displayed.)
I've started the function like this (found inside status-date.js file):
function displayStatus(fromDate,toDate) {
todayDate = new Date();
// this is a comment for code that needs to be written:
//
// magic happens here that compares today's date to the fromDate and toDate
// and returns th appropriate status line
//
// the rest below is how I think the status is returned to the html
// (I'm using 'in progress' as a test example)
var dateStatus = "in progress"
return dateStatus;
}
Note: the function is loaded in from the head section as follows:
<script src="assets/js/status-date.js" language="javascript" type="text/javascript"></script>
Even with this simple function.. that basically gives me the status without any calculations, just so I can test the comunication between HTML and function.. it doesn't display anything. So I can't really move forward until I figure out this basic step first.
So, could some kind sole help me figure this out.
How to properly send formated date parameters to the javascript function.
How to display the status results that need to be returned to the html
How do you (inside the function) check if todays date falls within a range of provided dates.
Thanks for any help provided.
SunnyOz
I believe that you are looking for something like this...
function displayStatus(fromDate,toDate) {
var status;
var today = new Date();
today = Date.parse(today);
if(today >= fromDate && today <= toDate) {
status = 'In Progress';
} else if(today > toDate) {
status = 'Workshop Finished';
} else {
status = 'Workshop To Come';
}
return status;
}
<script>
window.onload = function(){
var startDate = new Date(2014,1,6); //6th February
var endDate = new Date(2014,2,13); //13th March 2014
document.write(displayStatus(Date.parse(startDate), Date.parse(endDate)));
};
</script>
Here are some other helpful resources:
Compare two dates with JavaScript
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

How to compare datetime in javascript

I have been trying to get the code to work for more then 2 hours, then I tried this site, well there is alot of code here! I have used each of them. Some are in jQuery while some were pure JavaScript.
Here is two of the code that I have tried:
First code: This code was caught from this link: https://stackoverflow.com/a/2725097/1762944
var dateTimeStr = "17:10:03";
var user_time = DateTime.Parse( dateTimeStr );
var time_now = DateTime.Now;
if( time_now > user_time )
{
// your code...
}
Second code: This one is jQuery. It worked for the asker, and was marked as answer too. It works I have checked the fiddle provided by him! But when I tried the code, it didn't work either. Here:
function time_until() {
currentTime = Math.floor(jQuery.now() / 1000);
seconds = eventTime - currentTime;
if(second == 0){
//Stop voting
}
days = Math.floor(seconds / (60 * 60 * 24));
$('#time').html('seconds ' + seconds + '<br/>days ' + days);
}
I have tried to edit them both. But they don't work.
Reason why they work: The reason behind this all, is that what I want to do is,
I have a database table which is storing the time for users. I mean when they made an activity such like posting status updates!
I have created a timestamp. Which shows perfectly like this: few seconds ago.
Now what I want is, to update the time to 1 minute ago without reloading the page, like Facebook does. Or whatever the time is, to get updated to the next minute or hour or corresponding.
What I have tried is almost next to everything. But I guess the only issue with my codes is that when I place the DateTime.Now value from Database in it, it shows an error. The error is hidden so I have created an else statement like this:
if(seconds < 60) {
$("#jstime").html(seconds + "seconds..");
// else if minutes, if hours they are all written..and then an else
} else {
$("#jstime").html("Again an error, try again bud");
}
I have a setInterval which keeps on updating the id with the error text.
Here is the code that I am using.
<span id="timeval" title="#timeStamp">#TimeStamp</span></div>
<input type="hidden" id="time" value="9/23/2013 8:10:40 PM" />
<span>Real time: #TimeStamp</span><br>
<span id="update">Updated time: no update till now;</span><br>
<span id="jstime">Time</span>
The timeval is the real time that is being shown to the users, input is the time from where I get the value of the time on each post, the next span just shows the time to me, I mean I used this to check what was the time when the page was loaded, update is the span to show the updated time, jstime can also be used to show the updated time.
The problem is that you stored currentTime in the function you call every n seconds. As it gets looped it will everytime create a new current time.
Make it a global variable so you can loop through the function without creating the time new and use the old time instead.
Please go to link on stackoverflow and see my answer on how can we compare two dates along with the time in Javascript.

Categories

Resources