Need help fixing setInterval issue in JavaScript - javascript

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/

Related

javascript onclick to display time and date in a paragraph or not

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.

Javascript refresh time in HTML text box; getElementByID error

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.

How can I control a progress element using JavaScript for Loading visualization?

I need help with adding a loader to my HTML document. Here's the page without the loader:
<!DOCTYPE html>
<html>
<head>
<title>Webpage</title>
</head>
<body bgcolor="#FFFFFF">
<script>
/*
Script goes here for the loader.
I think I might have an idea, I could use the "load" event.
*/
</script>
<style>
h1 {
color: green;
font: 24px Courier;
}
.css-format-class {
color: red;
font: 16px Arial;
}
</style>
<center>
<h1>My Simple Webpage</h1>
</center>
<br>
<p class="css-format-class">I wish I could add a loader GIF onto this page...</p>
<!--I need a loader somewhere in this webpage...-->
<!--If you know the solution, please feel free to comment.-->
</body>
</html>
I found this bit of code in HTML5, but don't know how to make JavaScript manipulate this tag:
<progress id="loader" value="0" max="100"></progress>
If you know how, let me know.
Get a reference to the progress element (e.g. using document.getElementById()) and then update the value property, which maps to the attribute of the same name. See the snippet below for a demonstration, where setInterval() is used to call a function every second to update the value.
The code below waits until the DOM is ready by adding an event listener (using document.addEventListener()) to add a callback when the event DOMContentLoaded happens. That way it doesn't try to access elements in the DOM (e.g. the progress element) before it is ready.
var progress, date, interval;
// wait until DOM has been loaded to perform DOM Manipulations
document.addEventListener('DOMContentLoaded', function() {
date = Date.now(); //current timestamp since UNIX epoch
//get a reference to the progress element using its id attribute
progress = document.getElementById('loader');
interval = setInterval(updateProgress, 1000);
});
function updateProgress() {
msg.innerHTML = 'begin updateProgress() - progress.value = '+progress.value + "<br>" + msg.innerHTML;
if (progress.value >= 100) {
//stop running this function after value reaches 100 (percent)
clearInterval(interval);
}
var newDate = Date.now();
var milliseconds = newDate - date;
var seconds = Math.floor(milliseconds / 1000);
loader.value += seconds;
}
<progress id="loader" value="15" max="100"></progress>
<div id="msg" style="max-height:100px;overflow-y: auto"></div>

clearInterval() not working on clock timer with JavaScript

I am very new to JavaScript and programming in general. I am currently in a little pickle with some code that I am playing around with, and I am wondering if anyone can give me some advice.
Background:
The code I am working with is rather simple; There is a clock with the current time running on setInterval to update by the second.
Below the clock there is a button that reads “Stop,” and when pressed, it will clear the Interval and the button will then read “Start.” If the button, which reads “Start” is pressed again, it will continue the clock timer in its current time. So basically this one button toggles the interval of the clock, and depending on which state it is, the button will read “Start” or “Stop.”
W3Schools: JS Timing is where I am originally referencing when creating the code I am working with. This is where I am learning about how setInterval and clearInterval works. I also took some of the code in the examples and adjusted it so I can try to make the clock timer toggle off and on.
Code:
var clock09 = window.setInterval(myTimer09, 1000);
function myTimer09() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("req09").innerHTML =
"<h1>" + t + "</h1>";
}
function toggle10() {
var button = document.getElementById("button10").innerHTML;
if (button == "Stop") {
window.clearInterval(clock09);
document.getElementById("button10").innerHTML = "Start";
} else {
clock09 = window.setInterval(myTimer09, 1000);
document.getElementById("button10").innerHTML = "Stop";
}
}
<span class="center" id="req09"></span>
<button type="button" id="button10" onclick="toggle10()" class="button">Stop</button>
https://jsfiddle.net/dtc84d78/
Problem:
So my problem with the code is that the button toggles from a “Stop” button to a “Start” button, but the clearInterval is not applying to the Variable with the setInterval.
I have googled similar problems in SO, such as this one, and I followed their advice, and still nothing. After hours of trying to figure out, I decided to just copy and paste some example from W3Schools straight to jsFiddle, and that didn’t even work (included in jsfiddle link)?
I am really just going crazy on why anything with clearInterval() is not working with me? Could it be my computer, browser or anything else? I am coming to SO as my last resource, so if anyone can give me some guidance to this problem, I will name my first child after you.
Thank you in advance.
Extra Info:
I am currently working on a Mac desktop, using Komodo to write the code, and I am using Google Chrome to preview the code.
UPDATE:
I mentioned this in the comments, but coming in the code was in an external .js file. The .js file was then linked in between the head tags, and right before the end body tag.
<head>
<meta charset="utf-8" />
<title>Program</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/program-05.css">
<script type="text/javascript" src="scripts/program-05.js">
/* <![CDATA[ */
/* ]]> */
</script>
</head>
<body onload="checkCookies(); setTimeout(function() { func11() }, 5000);">
. . . code for stuff
. . . code for clock timer
. . . code for other stuff
<script type="text/javascript" src="scripts/program-05.js">
/* <![CDATA[ */
/* ]]> */
</script>
</body>
After #Matz mentioned to stick the clock timer js code in the head section, the code worked great! This is what it looks like so far in the head section.
<head>
<meta charset="utf-8" />
<title>Program</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/program-05.css">
<script type="text/javascript" src="scripts/program-05.js">
/* <![CDATA[ */
/* ]]> */
</script>
<script>
///*
var clock09 = window.setInterval(myTimer09, 1000);
function myTimer09() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("req09").innerHTML =
"<h1>" + t + "</h1>";
}
function toggle10() {
var button = document.getElementById("button10").innerHTML;
if (button == "Stop") {
window.clearInterval(clock09);
document.getElementById("button10").innerHTML = "Start";
} else {
clock09 = window.setInterval(myTimer09, 1000);
document.getElementById("button10").innerHTML = "Stop";
}
}
//*/
</script>
</head>
Though this works great, I now want to figure out as to why the clock timer js code works when it is directly in the head section as compared to keeping it in the external .js file (with the external file being linked in the doc)? What can I do to make it work within the external file?
Problem:
This is because the default Load Type is set to onLoad which is wrapping your javascript code in window.onload = function() {} hence the scope of your function was getting limited to the onload function and it wasn't available outside:
Solution:
Click on the Javascript setting in the Javascript section of the Fiddle, change it to No wrap - in body and it will work since this will now place your Javascript code in the body tag.
Additional Note:
Your code is also working via StackOverflow snippet:
/*My Problem*/
var clock09 = window.setInterval(myTimer09, 1000);
function myTimer09() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("req09").innerHTML =
"<h1>" + t + "</h1>";
}
function toggle10() {
var button = document.getElementById("button10").innerHTML;
if (button == "Stop") {
window.clearInterval(clock09);
document.getElementById("button10").innerHTML = "Start";
} else {
clock09 = window.setInterval(myTimer09, 1000);
document.getElementById("button10").innerHTML = "Stop";
}
}
/*W3S Problem*/
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML =
d.toLocaleTimeString();
}
<!-- My Problem -->
<span class="center" id="req09"></span>
<button type="button" id="button10" onclick="toggle10()" class="button">Stop</button>
<hr>
<hr>
<!-- W3S Problem -->
<p id="demo"></p>
<button onclick="clearInterval(myVar)">Stop time</button>
Recommendation
Separation of concerns
I'll recommend you moving your javascript code in the external file and later include them in your HTML using script tag. So for example, you moved your code in app.js then include that in your HTML as:
<!-- make sure the path here is relative to the current HTML -->
<script src="./app.js"></script>
One way to fix the timer starting and stopping is to move the javascript in between the HEAD tags so the functions are declared by the time the html loads. I made this work:
<html>
<head>
<title>Stuff</title>
<script >
var clock09 = window.setInterval(myTimer09, 1000);
.... your code
</script>
</head>
<body>
<span class="center" id="req09"></span>
<button type="button" id="button10" onclick="toggle10()" class="button">Stop</button>
</body>
</html>
You are declaring a new date variable in the myTimer09 function, so every time it is called, it shows the current time. You should declare the time outside the function, then pass it to the function. When you stop the timer, you should save the time value so that you can restart with that value.
This seems to be an issue with JSFiddle.
The onclick handler is looking for window.toggle10 which isn't actually defined (check for the error in the console).
It seems that this is something others have seen with JSFiddle
I've C&Ped your code in to a JSbin and it works as described!

Jquery or Javascript that display content based on the date HELP

Jquery or JavaScript that displays content based on specifics date period
so we have like 3 dates
12/3/2010
12/11/2010
12/20/2010
and
Div Contents
Content 1 should be displaying from 12/3 to 12/11
Content 2 should be display from 12/11 to 12/20
and Content 3 should be displaying from 12/20 there after
First, like others said this whole thing is bad idea as you're depending on the client machine date/time and correct approach would be doing that in server side.
Anyway, guess you have your reasons so here is jQuery solution.
Have such HTML:
<div class="DateDiv"><span class="DateRange">1/1/2010 to 1/1/2011</span>I'll be visible during 2010</div>
<div class="DateDiv"><span class="DateRange">1/1/2011 to 1/1/2012</span>I'll be visible during 2011</div>
<div class="DateDiv"><span class="DateRange">1/1/2012 to 1/1/2013</span>I'll be visible during 2012</div>
Put the date range inside a span inside each div with the class "DateRange".
Next, have such CSS to have them initially hidden:
<style type="text/css">
.DateRange, .DateDiv { display: none; }
</style>
And finally, this script: (jQuery)
<script type="text/JavaScript">
$(function() {
$(".DateDiv").each(function(index) {
var sRange = $(this).find(".DateRange").html();
var arrTemp = sRange.split(" to ");
var dtFrom = new Date(arrTemp[0]);
var dtTo = new Date(arrTemp[1]);
var dtNow = new Date();
if (dtNow >= dtFrom && dtNow <= dtTo)
$(this).show();
});
});
</script>
Test case is available here feel free to mess around with it: http://jsfiddle.net/2BHLd/
I've created a simple code. It should work as you want (if I have understood you well).
I know, there's no doctype in my HTML and there are some missing tags. The HTML I've provided is just a kind of template.
<html>
<head>
<script type="text/javascript">
var date=new Date();
var year=date.getFullYear();
var month=date.getMonth();
var day=date.getDate(); // fixed
function SetDivContent() {
var div=document.getElementById('date_dependent');
if (year==2010 && month==11) { // fixed (the JavaScript months order is 0-11, not 1-12)
if (day>=3 && day<11) { // the following content will be displayed 12/03/2010, 12/04/2010, [...], 12/09/2010, 12/10/2010
div.innerHTML='content 1';
}
else if (day==11 || day==12) { // this one will be displayed 12/11/2010 and 12/12/2010
div.innerHTML='content 2';
}
else if (day>12) { // this one - 12/13/2010 and later, until the end of December
div.innerHTML='content 3';
}
}
else if (year==2011 && month>=0) div.innerHTML='content 3'; // OPTIONAL - just to ensure that content 3 is displayed even after December.
}
</script>
</head>
<body onload="SetDivContent()">
<div id="date_dependent"></div>
</body>
</html>
Please note that if you want to hide some data from users if the specified date hasn't come yet, you should better use something server-side for security reasons. Otherwise, any user may just read the page's source. Also remember that the following code is executed when the body is loaded, i.e. each time a user refreshes the page.
EDIT: Warning: there were two bad lines (I've made a mistake before). Anyway, I've fixed them. The current code works, I've tested it.

Categories