I am trying to have the time display every second in an HTML page, in a text box, but I just get the error message that getElementByID does not exist. My code is below. Nothing displays with the code below. can you please correct me, or point out what I am missing?
function getTime() {
var currentDate = new Date();
var date = currentDate.toLocaleString();
document.getElementById("clock").innerHTML = date;
}
var repeatedTime = setInterval("getTime()", 1000);
getTime();
Here is my HTML code:
<!DOCTYPE html>
<html>
<head>
<script src="clockjavascript.js" ></script>
</head>
<body>
<form>
<input id="clock" type="text" />
</form>
</body>
</html>
Thank you to Daniel Szabo, for he solved this problem. The correct javascript which works with the HTML is below. I needed to change document.getElementById("clock").innerHTML to .value.
function getTime() {
var dateObject = new Date();
var dateString = dateObject.toLocaleString();
document.getElementById("clock").value = dateString;
}
var repeatedTime = setInterval(getTime, 1000);
getTime();
Four issues
Use getElementById instead of getElementByID ("d" needs to be lowercase")
Use document.getElementById("clock").value instead of innerHTML to manipulate the contents of a textbox
Try setInterval(getTime, 1000); instead of setInterval("getTime()", 1000);
Move the <script src="clockjavascript.js"></script> tag to the bottom of the page, just before the </body> tag. That way the <input> element being acted upon is rendered and available to be acted upon when the script executes.
For a quick test, you can paste this into your browser console and watch the time tick away.
function getTime() {
var currentDate = new Date();
var date = currentDate.toLocaleString();
console.log(date);
}
var repeatedTime = setInterval(getTime, 1000);
getTime();
Your syntax is slightly off - it's
getElementById
Rather than
getElementByID
The latter doesn't exist as a method.
Related
Currently, I have this in my HTML code and am not 100% sure on how to redirect to another page I have after the countdown finishes. I am not too familiar with javascript at the moment either, any help is appreciated. I know that when the page loads it takes the current time ( at the .now snippet) and just adds 10 seconds to it rather than a set time the script should end at then display the difference between present and that set time. The issue with this is that when anyone loads this page it would always show a countdown for 10 seconds to it rather than a universal countdown. For example, the time currently is 3:53 and should end at 4:00. Once the time hits 4 push the redirect.
<!--Countdown Script -->
<script type="text/javascript">
$(document).ready(function() {
$('#countdown17').ClassyCountdown({
theme: "flat-colors-very-wide",
end: $.now() + 10
});
});
</script>
You want to get the time from a fixed one. So, utilize Date built-in API instead of jQuery's $.now(), because
This API has been deprecated in jQuery 3.3; please use the native Date.now() method instead.
What time do you want? Determine it beforehand (GMT):
const date1 = new Date('September 13, 2021 04:00:00');
Then, when subtracting the dates you'll get the time remaining.
<!--Countdown Script -->
<script type="text/javascript">
$(document).ready(function() {
$('#countdown17').ClassyCountdown({
theme: "flat-colors-very-wide",
end: date1 - new Date() // gets the difference between determined date and current date
onEndCallback: () => {
window.location.href = "http://www.example.com";
}
});
});
</script>
Remember to handle the case when the time of access was after the pre-defined time.
add a callback parameter (function) to your countdown
<!--Countdown Script -->
<script type="text/javascript">
$('#countdown17').ClassyCountdown({
theme: "flat-colors-very-wide",
end: $.now() + 10,
onEndCallback: function () {
window.location.href = "http://www.newlink.com";
}
});
</script>
If you're trying to redirect and doesn't matter if is using javascript or not, use the tag from the HTML.
<meta http-equiv="refresh" content="10; URL="https://www.mywebsite.com.br/" />
It will count to 10 and redirect to your URL
I'm assuming this is the ClassyCountdown() jQuery plugin you are using: https://github.com/arsensokolov/jquery.classycountdown
If that's the case, it has an onEndCallback which is called once the countdown reaches 0.
So your code would become something like this:
<!--Countdown Script -->
<script type="text/javascript">
$(document).ready(function() {
$('#countdown17').ClassyCountdown({
theme: "flat-colors-very-wide",
end: $.now() + 10,
onEndCallback: function () {
document.location.href = 'https://www.google.com' // <- The url to redirect to
}
});
});
</script>
Updated answer to redirect at an absolute time:
$(document).ready(function() {
setInterval(function() {
// This is when you want the redirect to happen
// This is the absolute time, as reported by the users browser
let hour = 21;
let minute = 18;
let second = 20;
let date = new Date();
if (date.getHours() == hour && date.getMinutes() == minute && date.getSeconds() >= second) {
document.location.href = 'https://www.whatever.com';
}
}, 1000);
});
I'm trying to get the date to appear in an empty paragraph with an ID when I click on a button. So far no luck. Don't mind if I cant get it to appear in the paragraph but just want to know how to make it appear when I click the button thanks in advance.
sorry if its a dumb one,
I have got the alert working on click but just can not seem to figure this one out
<!DOCTYPE html>
<html>
<head>
<title>Lets Practice Some Code</title>
<link rel="stylesheet" type="text/css" href="/Users/Matteveli/Desktop/javascript practice/style/style.css">
</head>
<body>
<div><h1 id="topTitle"> Time and date Test</h1></div>
<div><button id="alerter">click Me to make an alert pop up.</button></div>
<p id="empty"
></p><div><button id="timeAndDate">click Me to display time and date</button></div>
<script type="text/javascript" src="/Users/Matteveli/Desktop/javascript practice/javascript/funtionality.js"></script>
</body>
<footer>
</footer>
</html>
var alerterButton = document.getElementById("alerter");
var dateButton = document.getElementById("timeAndDate");
var emptyP = document.getElementById("empty");
var d = new Date();
// for the first click that we have working.... " THE ALERT "
//a link to function was called then the function was made
// as below
alerterButton.onclick = myClickHandler;
function myClickHandler() {alert("the document was clicked")};
/// TIME AND DATE ???
dateButton.onclick = emptyP.innerHTML=d;
function showMeTheDate() {emptyP.innerHTML+d};
any help greatly appreciated.
thanks in advance.
Here an example: http://jsfiddle.net/sckjnx7t/2/
The key is engage function and event, in this case onclick, then, you could do:
dateButton.onclick = function(){
//code here
};
or:
dateButton.onclick = showMeTheDate();
function showMeTheDate() {
//code
};
dateButton.onclick should be a function. So, you should do
dateButton.onclick = () => { emptyP.innerHTML= d.getDate() }
Only edit your event handler function, and set pharagraph's innerHTML to d.getDate().
function myClickHandler() {
alert("button was clicked!");
emptyP.innerHTML = d.getDate();
}
You need to stay the function workers in same scope. Without this approach, the latest eventHandler function will be used for all time, because other (last) functions' functionality won't be.
Yesterday, I was informed about setInterval to perform a task or function after a certain number of milliseconds. I have the interval working in my code, but each time it creates a new text line with the date. I want it to replace the previous one after each interval has ended. I tried fixing this by defining the text and date as a variable to be called, but that doesn't work either. Also, for anybody who is interested, here's the link to my question yesterday, which received very helpful responses.
<html>
<head>
<title>Time Stuff Page</title>
</head>
<link href="main.css" rel="stylesheet" type="text/css">
<body>
<!-- adding color style for demo date buttons via CSS style tag->
<style type="text/css">
#demo {
color:red;
}
#demo2 {
color:blue;
}
</style>
<!-- Display date in paragraph -->
<button onclick="getElementById('demo').innerHTML=Date()">The time is? (from innerhtml)</button>
<p id="demo"></p>
<!-- Display date by calling a JS function -->
<button onclick="displayDate()">The time is? (from javascript)</button>
<p id="demo2"></p>
<!-- Display date inside "this" button -->
<button onclick="this.innerHTML=Date()">The time is? (display in button)</button>
<p></p>
<script language="javascript">
function displayDate() {
document.getElementById("demo2").innerHTML = Date();
}
var savedate = Date();
document.write("You loaded the page at: "+savedate);
//constantly updated date();
constantDate = function() {
var date = Date();
var timetext = "<br />Updated time is: "+date;
document.write(timetext);
}
function checkDate() {
setInterval(function(){ constantDate(); }, 10);
}
checkDate();
</script>
</body>
</html>
Create similar function to displayDate:
function displayDate2() {
var timetext = "Updated time is: "+Date();
document.getElementById("demo3").innerHTML =timetext;
}
You also need to add another paragraph to the body:
<p id="demo3"></p>
The problem is that your JavaScript file is calling the "checkDate()" function as soon as it runs. This means it will run the "constantDate()" function, and this function is using document.write to output the result.
Therefore it will be spamming your document with that output, instead of inserting it in a div. Set it to insert in a div inside the "constantDate()" function like this, and then create the div, and everything should be fine:
constantDate = function() {
var date = Date();
var timetext = "<br />Updated time is: "+date;
document.getElementById("demo3").innerHTML = timetext;
}
And create the div class:
<p id="demo3"></p>
Also, it's usually, like almost always, better to separete your HTML code and JavaScript code, so instead of adding JS code or functions to your "onclick=" property on the button's HTML, add click events in your JS like so:
HTML:
<button id="button2">The time is? (from javascript)</button>
JavaScript:
/* On click event for button 2 */
var button2 = document.getElementById('button2');
button2.onclick = function() {
displayDate();
}
Check this JS Fiddle I've done for you: http://jsfiddle.net/filipetedim/t0to0hL8/
I've a jsp page which sets 'timestamp' attribute to certain HTML elements. I use the value of these 'timestamp' to display time elapsed in the format - "updated 10 seconds ago" (as tooltips)
I've created a static HTML page for the demonstration of my issue.
This is my code:
<html>
<head>
<script type = "text/javascript">
function setTime() {
var currentDate = new Date();
var elem = document.getElementsByClassName('supermaxvision_timestamp');
if(elem) {
for (var i = 0; i < elem.length; i++) {
var timestamp = elem[i].getAttribute('timestamp');
if(timestamp) {
var startTimestamp = new Date();
startTimestamp.setTime(timestamp)
var difference = currentDate.getTime() -startTimestamp.getTime();
elem[i].innerHTML = difference + " milliseconds";
}
}
}
setInterval(setTime, 1000);
}
</script>
</head>
<body>
<div class='supermaxvision_timestamp' timestamp='1353389123456' ></div>
<div class='supermaxvision_timestamp' timestamp='1353389234567' ></div>
<div class='supermaxvision_timestamp' timestamp='1353389345678' ></div>
<div class='supermaxvision_timestamp' timestamp='1353389456789' ></div>
<div class='supermaxvision_timestamp' timestamp='1353389567890' ></div>
<button onclick="setTime()">start</button>
</body>
</html>
you can just copy paste this code into a text file and open it in a browser (click 'start' button only once).
The problem is that initially the values of my div will update once every second ( as the code - setInterval(setTime, 1000)). But slowly the update interval decreases and values gets updated instantaneously. And within a minute the browser stops responding.
I'm not calling setInterval from within the loop. What is possibly wrong here?
Also, this code doesn't work in IE.
setInterval(fn, ms) says run fn every ms milliseconds, from now until I clear this interval. But on each call, you set a new interval, identical to the last.
So simply change setInterval to setTimeout which does not repeat, and only calls the function provided once. setTimeout can emulate setInterval by calling a function that sets a new timeout recursively. If you do that with intervals, you schedule more and more intervals that never stop. And each time it calls itself, the number of scheduled intervals double. It gets out of hand quickly...
Alternatively, you can move the setInterval out of the setTime function and only call it once, which will keep it being called every second. Like say:
// button calls this.
function startTime() {
setInterval(setTime);
}
function setTime() {
// all that code, but minus the setInterval at the end
}
You're calling setInterval recursively. Every time a new interval is created, that interval creates a new interval. Eventually the browser cannot handle it.
Maybe you would rather something like this?
<button onclick="setInterval(setTime, 1000)">start</button>
setInterval begins a repeating function - as it is right now setTime does it's loop and logic then calls setTimeout every second, each setTimeout call then starts another repeated call to itself every second. if you use setTimeout instead, it will be called once only, but my suggestion would be that instead you simply run setInterval outside your function declaration, like:
<html>
<head>
<script type = "text/javascript">
function GEBCN(cn){
if(document.getElementsByClassName) // Returns NodeList here
return document.getElementsByClassName(cn);
cn = cn.replace(/ *$/, '');
if(document.querySelectorAll) // Returns NodeList here
return document.querySelectorAll((' ' + cn).replace(/ +/g, '.'));
cn = cn.replace(/^ */, '');
var classes = cn.split(/ +/), clength = classes.length;
var els = document.getElementsByTagName('*'), elength = els.length;
var results = [];
var i, j, match;
for(i = 0; i < elength; i++){
match = true;
for(j = clength; j--;)
if(!RegExp(' ' + classes[j] + ' ').test(' ' + els[i].className + ' '))
match = false;
if(match)
results.push(els[i]);
}
// Returns Array here
return results;
}
function setTime() {
var currentDate = new Date();
var elem = GEBCN('supermaxvision_timestamp');
if(elem) {
for (var i = 0; i < elem.length; i++) {
var timestamp = elem[i].getAttribute('timestamp');
if(timestamp) {
var startTimestamp = new Date();
startTimestamp.setTime(timestamp)
var difference = currentDate.getTime() -startTimestamp.getTime();
elem[i].innerHTML = difference + " milliseconds";
}
}
}
}
</script>
</head>
<body>
<div class='supermaxvision_timestamp' timestamp='1353389123456' ></div>
<div class='supermaxvision_timestamp' timestamp='1353389234567' ></div>
<div class='supermaxvision_timestamp' timestamp='1353389345678' ></div>
<div class='supermaxvision_timestamp' timestamp='1353389456789' ></div>
<div class='supermaxvision_timestamp' timestamp='1353389567890' ></div>
<button onclick="setInterval(setTime, 1000)">start</button>
</body>
</html>
Also, the reason this is not working in IE is that it does not properly support the getElementsByClassName method of document. I found that out here: IE 8: Object doesn't support property or method 'getElementsByClassName' and Rob W also gives a good explanation there, but for a quick answer I have modified my code above to work in IE, using querySelectorAll
Derp, thats a jQuery method Chris, why would you just assume people use jQuery. getElementsByClassName & IE8: Object doesn't support this property or method includes an answer from ascii-lime which implements it's own version of getElementsByClassName. There no benefit to me copying all the code to here, but go have a look if you don't want to use jQuery.
OK, I just said there was no point, but I've copied all the code here anyway, above is a working, tested (on ie and ff) example of what you want
I'm very new to javascript and I'm trying to do something I thought would be very basic.
I've created a countdown timer and used "i" as my variable to hold a number from 0-5. And I have an array of "d" from d[0] to d[5] containing strings.
I'm trying to make the timer countdown pass the "i" value into an innerHTML method array value so I want it to display d[5]... d[4]...d[3]... etc.
What am I doing wrong!? Please Help!
<html><head><script language="javascript" type="text/javascript">
var d=new Array():
d[1]="One";
d[2]="Two";
d[3]="Three";
d[4]="Four";
d[5]="Five";
var i=5;
var i=setInterval("timer()",2000); //1000 will run it every 1 second
function timer() {
i--;
if (i <= 0)
clearInterval(countD);
return;
}
}
document.getElementById(timer).innerHTML = d[i];
</script>
</head>
<body>
<h1>
<p id="timer"></p>
</h1>
</body>
</html>
Also, document.getElementById(timer).innerHTML = d[i];
should be document.getElementById("timer").innerHTML = d[i];
id names need to have quotes around them because they are not names of variables. The variable 'timer' is undefined.
Also, you are missing a curly brace on the line if (i <= 0). I am assuming that you meant to exit the function if this if statement is true.
Also, you have a colon instead of a semicolon on the line var d=new Array():
Also, you can't have a paragraph tag inside of an h1
Also, you should encapsulate all of this javascript into a function called something like init. I believe that the javascript code in the head runs before the html is loaded. The javascript can't therefore find the tag. Then, use <body onload="init()"> as your body tag.
EDIT: As the commenters have stated, you are using the variable i for multiple unrelated things.
I'm sorry to say but your code is quite a mess; here's one way to get your code to work, along with a working example:
<html>
<head>
<script language="javascript" type="text/javascript">
var d=new Array();
d[0]="One";
d[1]="Two";
d[2]="Three";
d[3]="Four";
d[4]="Five";
var i=4;
var myTimer =setInterval(timer,2000); //1000 will run it every 1 second
function timer() {
document.getElementById("timer").innerHTML = d[i];
i--;
if (i < 0){
clearInterval(myTimer);
}
}
</script>
</head>
<body>
<h1>
<p id="timer"></p>
</h1>
</body>
</html>
The problems with your JavaScript
You've got two declarations for i, one after the other - one is set to 5 and the other to the setInterval timer
What is countD in clearInterval(countD);?
document.getElementById(timer).innerHTML = d[i]; is attempting to use the function timer as the argument to getElementById. It should be in quotes: document.getElementById("timer").innerHTML = d[i];
It is also being invoked only once since it's not inside the function that is being called by the timer.
var d=new Array(): should be terminated by a ;(semi-colon) and not a : (colon)
You have unmatched braces - your if statement doesn't have an opening brace ({) but it does have a closing one.
Note that while setInterval("timer()", 1000) is valid JavaScript, it depends on eval which should be avoided if possible. The alternate, preferred way to use this is setInterval(timer, 1000) i.e. passing the function and not a string.