Work javascript according to checkbox's state - javascript

I have a checkbox that toggle the div and i register the choice to localstore and get it back
But the thing that i can't do is javascript that toggles the div won't see that checkbox's option it's needs to toggle it twice
index.html
<div id="siit" class="sit"></div>
Clock?: <br>
<label class="switch">
<input id="tetik" type="checkbox">
<span class="slider round"></span>
</label>
saat.js
function basla() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
h = checkTime(h);
m = checkTime(m);
s = checkTime(s);
document.getElementById('siit').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(basla, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
};
Here is the codepen: https://codepen.io/Etka/pen/BvGKWV
I want this: when user choose to show the clock and leave, when user comes back the javascript will check the checkbox if it's checked will show the clock

When checking the selected state and check the checkbox, also make the clock visible.
// Set the selected state
if (isSaved === "true") {
checkbox.checked = true;
$("#siit").show();
}

Change the css display property of the clock div element #siit to "block" inside your init() function if the checkbox is saved in LocalStorage by changing this:
if (isSaved === "true") {
checkbox.checked = true;
}
To this:
if (isSaved === "true") {
checkbox.checked = true;
document.getElementById("siit").style.display = "block";
}
Here is a CodePen with the above modified code that I forked from your original one: https://codepen.io/andrewl64/pen/LMXNgj?editors=0010

Related

My JS timer clock is not stopping when clicked twice on start button [duplicate]

This question already has an answer here:
JavaScript countdown timer with on key press to reset the timer
(1 answer)
Closed 11 months ago.
I have a simple HTML stopwatch logic where I can start and stop the clock with the button click. By clicking on the start button, one can start the timer (shows current time) and update every second. One can stop it by clicking stop button. But if one clicks on start button twice, there is nothing I can do to stop the timer. Below is my code:
var hour = document.getElementById("hoursOut");
var minute = document.getElementById("minsOut");
var second = document.getElementById("secsOut");
var btnStart = document.getElementById("btnStart");
var btnStop = document.getElementById("btnStop");
var waitTimer;
function displayTime() {
var currentTime = new Date();
var currentHour = currentTime.getHours();
var currentMinute = currentTime.getMinutes();
var currentSeconds = currentTime.getSeconds();
hour.innerHTML = twoDigit(currentHour) + ":";
minute.innerHTML = twoDigit(currentMinute) + ":";
second.innerHTML = twoDigit(currentSeconds);
}
function twoDigit(digit) {
if (digit < 10) {
digit = "0" + digit;
}
return digit;
}
function startClock() {
waitTimer = setInterval(displayTime, 1000);
}
function stopClock() {
clearInterval(waitTimer);
}
btnStart.onclick = startClock;
btnStop.onclick = stopClock;
<h1>JavaScript Clock</h1>
<div id="calendarBox">
<!-- OUTPUT TIME VALUES -->
<p class="timeDisplay">
<span id="hoursOut">00:</span>
<span id="minsOut">00:</span>
<span id="secsOut">00</span>
</p>
<!-- BUTTON SET -->
<input id="btnStart" type="button" value="START" />
<input id="btnStop" type="button" value="STOP" />
</div>
I have checked some answers in stackoverflow but most solutions uses a for-loop from 0 to 1000 until it finds the interval id and stop all of them using loop. I am confident there should be an elegant solution than that.
// some stackoverflow suggested answer
for (var i = 1; i < 99999; i++)
window.clearInterval(i);
A possible solution is to prevent the problem before it happens. You can place a check on the running timer (Is there a way to check if a var is using setInterval()?).
In this case you could just have a global timer variable var timer = false the with add a check to the start function. Then the stop function will set the timer variable back to false.
function startClock() {
if(!timer){
timer = true
waitTimer = setInterval(displayTime, 1000);
}
else return
}
function stopClock() {
clearInterval(waitTimer);
timer = false
}
when you double click you start a new setInterval(). So you now have two set intervals running. Only problem is you can't access the first one cause you named the second one the same name. Check if waitTimer exists and if it does stop it. see code:
UPDATE: actually you don't even need an if statement. just call stopClock() before you set waitTimer -- code snippet adjusted
var hour = document.getElementById("hoursOut");
var minute = document.getElementById("minsOut");
var second = document.getElementById("secsOut");
var btnStart = document.getElementById("btnStart");
var btnStop = document.getElementById("btnStop");
var waitTimer;
function displayTime() {
var currentTime = new Date();
var currentHour = currentTime.getHours();
var currentMinute = currentTime.getMinutes();
var currentSeconds = currentTime.getSeconds();
hour.innerHTML = twoDigit(currentHour) + ":";
minute.innerHTML = twoDigit(currentMinute) + ":";
second.innerHTML = twoDigit(currentSeconds);
}
function twoDigit(digit) {
if (digit < 10) {
digit = "0" + digit;
}
return digit;
}
function startClock() {
stopClock();
waitTimer = setInterval(displayTime, 1000);
}
function stopClock() {
clearInterval(waitTimer);
}
btnStart.onclick = startClock;
btnStop.onclick = stopClock;
<h1>JavaScript Clock</h1>
<div id="calendarBox">
<!-- OUTPUT TIME VALUES -->
<p class="timeDisplay">
<span id="hoursOut">00:</span>
<span id="minsOut">00:</span>
<span id="secsOut">00</span>
</p>
<!-- BUTTON SET -->
<input id="btnStart" type="button" value="START" />
<input id="btnStop" type="button" value="STOP" />
</div>

multiple alarm clock in javascript using dynamic generated input elements in javascript

I am trying to make a web page which will allow to set multiple alarms using dynamic element creation property of javascript but I'm not able to get the values of these multiple elements and create a alert on that time.
This is my code so far
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />
<script type="text/javascript">
var room = 0;
var i = 0;
function GetDynamicTextBox(){
return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
room++;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = document.getElementById('');
var minute = document.getElementById('');
var date = document.getElementById('');
}
</script>
To create a notification whenever a given time or state is reached, I think you are looking for setInterval (see reference).
This method allows you to take action at a regular interval and it tries to honor that interval the best it can. It opens to a common mistake if your action can take longer than that interval duration so be careful not using a too short interval. In such case, actions can overlap and weird behavior will occur. You do not want that to happen so don't be too greedy when using that.
For an alarm project, I would recommend an interval of one second.
Example (not tested):
JavaScript
var alarmDate = new Date();
alarmDate.setHours(7);
alarmDate.setMinutes(15);
// set day, month, year, etc.
var ONE_SECOND = 1000; // miliseconds
var alarmClock = setInterval(function() {
var currentDate = new Date();
if (currentDate.getHours() == alarmDate.getHours() &&
currentDate.getMinutes() == alarmDate.getMinutes()
/* compare other fields at your convenience */ ) {
alert('Alarm triggered at ' + currentDate);
// better use something better than alert for that?
}, ONE_SECOND);
To add dynamic alarms, you could put them into an array then have your setInterval iterate over it.
In the long run you will probably get sick of alert and feel the need to use something that doesn't break the flow of your application. There are a lot of possibilities, one being the use of lightboxes that could stack over each other. That way you would be able to miss an alarm and still be notified by the next one.
Hope this helps and good luck!
You forgot the ID attribute on the date input and you were collecting the input elements in AddAlarm instead of their values.
EDIT: To check the alarms you have to store them and check every minute, if the current date matches one of the alarms. I added a short implementation there.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnAdd" type="button" value="add" onclick="AddTextBox();" />
<script type="text/javascript">
var alarms = {};
var room = 0;
var i = 0;
setInterval(function() {
var current = new Date();
for (var nr in alarms) {
var alarm = alarms[nr];
console.log("checking alarm " + nr + " (" + alarm + ")");
if(current.getHours() == alarm.getHours()
&& current.getMinutes() == alarm.getMinutes()) { // also check for day, month and year
alert("ALERT\n"+alarm);
} else{
console.log('Alarm ' + nr + '('+alarm+') not matching current date ' + current);
}
}
}, 60000);
function GetDynamicTextBox(){
return '<div>Alarm ' + room +':</div><input type="number"style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" placeholder="hour" id="a'+room+'" /><input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" /><input type="date" style="margin:auto;text-align:center; width:200px; padding:10px" id="c'+room+'"><input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
room++;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = $('#a'+values).val();
var minute = $('#b'+values).val();
var date = $('#c'+values).val();
console.log(hour + ':' + minute + ' on ' + date);
var dateObj = new Date(date);
dateObj.setMinutes(minute);
dateObj.setHours(hour);
console.log(dateObj);
alarms[values] = dateObj;
}
</script>
So far I'm able to generate a alert when the values match the system time but I don't know how to delete the array value when an element is deleted. I am not able to do it. This is my code so far:
<script type="text/javascript">
var snd = new Audio("clock.mp3"); // buffers automatically when created
// Get
if (localStorage.getItem("test")) {
data = JSON.parse(localStorage.getItem("test"));
} else {
// No data, start with an empty array
data = [];
}
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
//since page reloads then we will just check it first for the data
function check() {
//current system values
console.log("inside check");
//if time found in the array the create a alert and delete that array object
for(var i = 0; i < data.length; i++) {
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
data.splice(i,1);
localStorage["test"] = JSON.stringify(data);
snd.play();
alert("Wake Up Man ! Alarm is over ");
}
}
if((data.length)>0)
{
setTimeout(check, 1000);
}
}
//we do not want to run the loop everytime so we will use day to check
for(var i =0 ; i< data.length; i++)
{
if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m) )
{
check();
}
}
console.log(data);
var room = 1;
//var data = [];
var i = 0;
function GetDynamicTextBox(){
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var d = date.getDay();
return '<div>Alarm ' + room +':</div><input type="number" style="text-align:center;margin:auto;padding:0px;width:200px;" min="0" max="23" value ='+h+' placeholder="hour" id="a'+room+'" /> <input type="number" min="0" max="59" placeholder="minute" style="text-align:center; padding:0px; margin:auto; width:200px;" id="b'+room+'" value ='+m+' /> <select id="c'+room+'" style="margin:auto; width:150px; padding:10px; color: black" required> <option value="1">Monday</option> <option value="2">Tuesday</option> <option value="3">Wednesday</option> <option value="4">Thursday</option> <option value="5">Friday</option> <option value="6">Saturday</option> <option value="0">Sunday</option> </select> <input type="button" value ="Set" onclick = "AddAlarm('+room+');" /> <input type="button" value ="Remove" onclick = "RemoveTextBox(this)" />';
}
function AddTextBox() {
room++;
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var html = "";
html += "<div>" + GetDynamicTextBox() + "</div>";
document.getElementById("TextBoxContainer").innerHTML = html;
}
window.onload = RecreateDynamicTextboxes;
function AddAlarm(values){
var hour = $('#a'+values).val();
var minute = $('#b'+values).val();
var date = $('#c'+values).val();
//get the current time and date
var today = new Date();
//current system values
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
//first check that whether a same date present in the array or not then push it
var found = -1;
for(var i = 0; i < data.length; i++) {
if (data[i].hours == hour && data[i].minutes == minute && data[i].dates == date ) {
found = 0;
break;
}
}
//if value does not present then push it into the array
if(found == -1)
{
data.push({hours: hour, minutes: minute, dates: date});
//storing it into localstorage
localStorage.setItem("test", JSON.stringify(data));
}
else
{
alert("Same value Exists");
}
//console.log(data);
function check() {
//current system values
//console.log("inside check");
//if time found in the array the create a alert and delete that array object
for(var i = 0; i < data.length; i++) {
var today = new Date();
var d = today.getDay();
var h = today.getHours();
var m = today.getMinutes();
if (data[i].hours == h && data[i].minutes == m && data[i].dates == d ) {
data.splice(i,1);
snd.play();
alert("Wake Up Man ! Alarm is over ");
}
}
if((data.length)>0)
{
setTimeout(check, 1000);
}
}
//we do not want to run the loop everytime so we will use day to check
for(var i =0 ; i< data.length; i++)
{
if((data[i].dates == d) && (data[i].hours >= h) && (data[i].minutes >= m))
{
check();
}
}
}
</script>

Real time agenda with javascript and json

I have a div on a website that needs to be a real time agenda for a list of events. I have the events loaded through a json file and am using javascript to populate the div with the data from the file.
The problem is that the data displays stacked item by item in one column within a div, I need to now split the div into three separate columns/divs. One for events happening now, next, and coming soon. Ex) one event is at 7am, next is 7:30, and coming soon is 8am.
But I am not able to select each item and move it using css since the code just populates by one item upon page load and I cannot see an index for each item (video side content item) over and over to display what events are necessary.
This would be a lot easier if I could just format the items being populated into three separate columns through css, but I can't figure out how to do this.
By the way this site is written using FlexBox, hence why there is a "row" in one of the divs.
Also can someone please point in the right direction as to how to get this to be real time? Or any other helpful solution that could achieve this?
Thanks in advance for any help.
picture of what I'm trying to do
Function to populate the data
function agendaRealTimeUpdate() {
if ($('.real-time-agenda').length !== 0) {
videoSideContentType = 'agenda';
$.getJSON("ac.json", function(data) {
var sessions = data.session;
var contentString = '';
var currentSessionIndex;
var currentSession;
var currentTime;
var currentDay;
var title;
var time;
var room;
var description;
var d;
var i = 0;
d = new Date();
//gets the current time and returns it in a string with 3-4 digits EX: "1000" = 10 am
currentTime = parseInt(d.getHours().toString() + ((d.getMinutes() < 10 ? '0' : '') + d.getMinutes()).toString());
currentDay = d.getDate();
// this loop runs as long as we haven't figured out which session matches the time
while (currentSessionIndex === undefined && i < sessions.length) {
//this takes the current time and compares it to the sessions start and end times
if ((currentTime >= sessions[i].startTime && currentTime <= sessions[i].endTime) &&
currentDay === sessions[i].day &&
sessions[i].track === "none")
{
currentSessionIndex = i;
}
i++;
}
if (currentSessionIndex === undefined) {
currentSessionIndex = 0;
}
// This function finds the sessions that come after the identified current session
function findNextSessions() {
var sessionsCopy = sessions.slice(); //make a copy of the sessions array so we aren't altering it when we remove indexes
for (var z = 0; z < 2; z++) {
var index = currentSessionIndex + z;
// breaks out of the loop if the next session is undefined
if (sessionsCopy[index] === undefined) {
z = 2;
}
currentSession = sessionsCopy[index];
// loops through the sessions and if the session has a track it is removed from the sessionsCopy array
while (currentSession.track !== "none") {
console.log('has a track: ' + currentSession.track);
sessionsCopy.splice(index, 1);
currentSession = sessionsCopy[index];
}
time = currentSession.timeString !== undefined ? "<div class='video-side-content__time'><b>Time:</b> " + currentSession.timeString + "</div>" : '';
room = currentSession.room !== undefined ? "<div class='video-side-content__room'><b>Room:</b> " + currentSession.room + "</div>" : '';
title = currentSession.title !== undefined ? "<div class='video-side-content__secondary-title'>" + currentSession.title + "</div>" : '';
description = currentSession.content !== undefined ? "<div class='video-side-content__content'>" + currentSession.content + "</div>" : '';
contentString += "<div class='video-side-content__item'>" + time + room + title + description + "</div>";
}
}
findNextSessions();
$('.real-time-agenda').html(contentString);
});
}
}
Div I'm working with
<div class="row__item">
<h2 class="video-side-content__title"><img src="img/agenda-icon.png"> Thursday. Sept. 22</h2>
<div class="row__flex-container">
<div class="row__item video-side-content__strip video-side-content__strip-left"> </div>
<div class="row__item video-side-content__row">
<div class="video-side-content">
<div class="video-side-content__items">
<div class="video-side-content__item">
<h2 class="count-down__sub-header"><br>
SHOWING NOW</h2><br>
<div class="real-time-agenda">
<!--data populates upon page load from the json file
It lays the data out as: Time, Title, Room, Description-->
</div>
<br>
</div>
</div>
</div>
</div>
</div>
</div>

Get events in full calendar given dates from DTP on button click. Jquery/Javascript

<p> From: </p>
<input type="date" id="from-date" class="form-control"/>
<p> To: </p>
<input type="date" id="to-date" class="form-control"/>
<p> From: </p>
<input type="date" id="from-date-copy" class="form-control"/>
<p> To: </p>
<input type="date" id="to-date-copy" class="form-control"/>
<input type="button" id="copy">
Hi guys, I have this first 2 date time pickers to set the span of dates to get in the FullCalendar, and the other set of 2 date time pickers where to copy the events.
Example I have..
1/13/2016 as start date
and
1/15/2016 as end date << DATE / EVENTS TO COPY
AND 1/20/2016 and 1/22/2016 <-- WHERE TO COPY
I will get all events from 1/13/2016 and 1/15/2016 and transfer the events to 1/20/2016 and 1/22/2016. Please help.
First picture:
Second picture:
I used this code :
function bindCopyEventsButton() {
$("#copy").click(function(event) {
var eventsInDay;
var eventsHolder = [];
var startDate = $("#from-date").val();
var endDate = new Date($("#to-date").val());
var whereToCopyStartDate = new Date($('#from-date-copy').val());
var whereToCopyEndDate = new Date($('#to-date-copy').val());
var whereToCopyStart = whereToCopyStartDate.getDate();
var whereToCopyEnd = whereToCopyEndDate.getDate();
var e1start = new Date(startDate);
var e1end = endDate == null ? e1start : endDate;
for (var d = e1start; d <= e1end; d.setDate(d.getDate() + 1)) {
//Get all events in the day
eventsInDay = getEventsInDay(d);
//For copy and paste. Will be used later. It's currently performing cut and paste
//eventsHolder.push(eventsInDay);
//Iterate all events in the day for updating
for(var e = 0; e < eventsInDay.length; e++) {
//Check if still applicable
if(whereToCopyStart <= whereToCopyEnd){
//Get start hour of the event
var startTimeHour = eventsInDay[e].start._i.getHours();
console.log("startTimeHour : " + startTimeHour);
//Get end hour of the event
var endTimeHour = eventsInDay[e].end._i.getHours();
console.log("endTimeHour : " + endTimeHour);
//Get start date of the event
var x = eventsInDay[e].start._i.getDate();
console.log("Start date.getDate : " + x);
//Get end date of the event
var y = eventsInDay[e].end._i.getDate();
console.log("End date.getDate : " + y);
//Set start date of the event to the value of the from date
eventsInDay[e].start._i.setDate(whereToCopyStart);
//If the start date and end date are the same use same end date. else start date + 1
if(x == y){
eventsInDay[e].end._i.setDate(whereToCopyStart);
} else {
eventsInDay[e].end._i.setDate(whereToCopyStart + 1);
}
console.log("Event GET START DATE : " + eventsInDay[e].start._i.getDate());
console.log("Event GET END DATE : " + eventsInDay[e].end._i.getDate());
//Set the start hours of event
eventsInDay[e].start._i.setHours(startTimeHour);
//Set the end hours of event
eventsInDay[e].end._i.setHours(endTimeHour);
//Update Calendar
$('#preferred-schedule').fullCalendar('updateEvent', eventsInDay[e]);
//Add 1 to the **where to copy** start date
whereToCopyStart = (whereToCopyStart + 1);
}
}
}
});
}
function getEventsInDay(date) {
return $('#preferred-schedule').fullCalendar('clientEvents', function(evt) {
if (date >= evt.start && date <= evt.end) {
return true;
}
});
}
I think I'm getting the right info. but again. The clientEvents doesn't get the events in the day. and the updateEvent doesn't reflect on the FullCalendar. But when I'm debugging I think I'm getting the right infos based on the logs.
The value comparisons are not completely correct (you will need to do some date manipulations), but I think this is kind of what you're looking for, using the clientEvents and updateEvent methods of FullCalendar:
//Find all the events that match the criteria
var events = $('#calendar').fullCalendar('clientEvents', function(evt){
if(evt.start >= $('#from-date').val() && evt.end <= $('#to-date').val()){
return true;
}
return false;
});
//Loop through the events and update them
for(var e = 0; e < events.length; e++){
events[e].start = $('#from-date-copy');
events[e].end = $('#to-date-copy');
$('#calendar').fullCalendar('updateEvent', events[e]);
}
Hopefully this gives you a push in the right direction.
Maybe Helpful Hint
To see how the clientEvents function works and what format it
returns data in, you can use the fullCalendar demo
(http://fullcalendar.io/js/fullcalendar-2.6.0/demos/agenda-views.html).
Open Chrome DevTools and use this function: var events =
$('#calendar').fullCalendar('clientEvents', function(evt){return
true;}); then print out events.

Why does the text keep repeating without a for loop?

I am making a code that will give two different types of clocks depending on the radio button selected. When the clock appears, the text saying "Reload the page to go back to clock settings. However, when the 12 hour clock radio button is selected, the text is repeated every second. Is there any way to fix this? And please do not use J Query, I do not know it.
function clock_12() {
document.write("<div align='center' style = 'background:#420080; color:limegreen'>"+"Reload the page to go back to the clock settings."+"</div>");
var clocktime = new Date();
var hours = clocktime.getHours();
var mins = clocktime.getMinutes();
var secs = clocktime.getSeconds();
var ampm = (hours >= 12) ? "P.M." : "A.M.";
if (hours >= 13) {
hours -= 12;
}
if (hours < 1) {
hours = 12;
}
if (mins < 10) {
mins = "0" +mins;
}
if (secs < 10) {
secs = "0" +secs;
}
document.write("<div id = 'the_clock' align = 'center' style = 'background:#420080; color:limegreen'></div>");
var div_clock = document.getElementById("the_clock");
div_clock.innerHTML = hours + ":" +mins+ ":" +secs+ " " +ampm;
setTimeout("clock_12()", 1000);
}
function clock_24() {
var clocktime = new Date();
var hours = clocktime.getHours();
var mins = clocktime.getMinutes();
var secs = clocktime.getSeconds();
var back = "Reload the page to go back to the clock settings.";
document.writeln("<div align='center' style = 'background:#420080; color:limegreen'>"+back+"</div>");
if (mins < 10) {
mins = "0" +mins;
}
if (secs < 10) {
secs = "0" +secs;
}
document.write("<div id = 'clock' align = 'center' style = 'background:#420080; color:limegreen'</div>");
var div_clock = document.getElementById("clock");
div_clock.innerHTML = hours + ":" +mins+ ":" +secs;
setTimeout("clock_24()", 1000);
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>12 and 24 Hour Clocks</title>
</head>
<body style="background:limegreen">
<table style="width:50%" align = "center">
<tr>
<td><script type = "text/javascript" src = "clock.js"></script></td>
</tr>
<tr>
<br /><br /><td style = "background:#420080; color:limegreen"><label for="clock12">12 Hour Clock</label><input type = "radio" onclick = "clock_12()" id = "clock12" value = "clock12"></td>
<br /><br /><td style = "background:#420080; color:limegreen"><label for="clock24">24 Hour Clock</label><input type = "radio" onclick = "clock_24()" id = "clock24" value = "clock24"></td>
</tr>
</table>
</body>
</html>
You have the line
document.write("<div id = 'clock' align = 'center' style = 'background:#420080; color:limegreen'</div>");
Inside your clock_24 function, which gets called every second because of this: setTimeout("clock_24()", 1000);. The same for clock_12. So, remove those lines from your functions. Put it outside, like at the beginning of the file clock.js. Check http://www.w3schools.com/jsref/met_win_settimeout.asp
EDIT: sorry, it is more than one line. You have do put all of your document.write outside of your functions.
EDIT: roshen_amin correctly commented that the html needs to be written on click. So the complete solution is to make a function that does the document.write, and then calls clock_24()/clock_12(). On click, call that function instead of clock_24()/clock_12(). Like that, the html appears when you click, but only the rest of the function is called every second

Categories

Resources