Why does this clock script fail on IE8? - javascript

http://home.comcast.net/~vonholdt/test/clock/index.htm
when the number on the right side, which shows the seconds, passes 7 all the other numbers flip to their following number until for 3 seconds (I mean until the right second number arrives to 0).
this only occurs in IE 8.
JS :
<script type="text/javascript">
$(document).ready(function(){
$('#wrap').animate({opacity: 0.0}, 0);
function middle(){
wrapTop = ($(window).height() - $('#wrap').height())/2;
wrapLeft = ($(window).width() - $('#wrap').width())/2;
$('#wrap').animate({marginTop: wrapTop, marginLeft: wrapLeft}, 500);
};
middle();
$(window).bind('resize', middle);
function checktime(prevhour,prevmins,prevsecs){
var now = new Date();
var hour = now.getHours();
if(hour < 10) hour = "0" + hour;
var mins = now.getMinutes();
if(mins < 10) mins = "0" + mins;
var secs = now.getSeconds();
if(secs < 10) secs = "0" + secs;
var hour = hour + "";
var mins = mins + "";
var secs = secs + "";
if(prevhour != hour) {
var prevhour = prevhour + ""
var hoursplit = hour.split("");
var prevhoursplit = prevhour.split("");
if(prevhoursplit[0] != hoursplit[0]) numberflip('#hourl',hoursplit[0]);
if(prevhoursplit[1] != hoursplit[1]) numberflip('#hourr',hoursplit[1]);
};
if(prevmins != mins) {
var prevmins = prevmins + ""
var minsplit = mins.split("");
var prevminsplit = prevmins.split("");
if(prevminsplit[0] != minsplit[0]) numberflip('#minl',minsplit[0]);
if(prevminsplit[1] != minsplit[1]) numberflip('#minr',minsplit[1]);
};
if(prevsecs != secs) {
var prevsecs = prevsecs + ""
var secsplit = secs.split("");
var prevsecsplit = prevsecs.split("");
if(prevsecsplit[0] != secsplit[0]) numberflip('#secl',secsplit[0]);
if(prevsecsplit[1] != secsplit[1]) numberflip('#secr',secsplit[1]);
};
function numberflip(which,number){
if(number != 0) $(which).animate({marginTop: '-'+parseInt((number*140),10)+'px'}, 250, 'linear');
if(number == 0) {
var getmargin = parseInt(($(which).css('margin-top')), 10);
$(which).animate({marginTop: parseInt((getmargin-140),10)+'px'}, 250, 'linear', function(){
$(this).css("margin-top","0px")
});
};
};
setTimeout(function(){checktime(hour,mins,secs);}, 200);
};
checktime(00,00,00);
$('#wrap').animate({opacity: 1.0}, 1000);
});
</script>
HTML :
<div id="wrap">
<img id="hourl" class="time" src="nums2.png" />
<img id="hourr" class="time" src="nums10.png" />
<img class="time" src="colon.png" />
<img id="minl" class="time" src="nums6.png" />
<img id="minr" class="time" src="nums10.png" />
<img class="time" src="colon.png" />
<img id="secl" class="time" src="nums6.png" />
<img id="secr" class="time" src="nums10.png" />
<div style="clear:left;"> </div>
<div id="cover"> </div>
</div>

Related

Time difference calculating program being slightly off

I'm fairly new to JS and making a program that's supposed to count the number of days in between the given date and current date. Then it's supposed to calculate the number of years, months and remaining days between them from the calculated days. It's off by a couple of days for bigger dates. Any help would be greatly appreciated.
I've been trying it on dates such as 23.01.2076 and 23.01.1940 and changing the year and month one up or one down. For most of them it's off by 1-3 days.
HTML:
<html>
<head>
<meta charset="utf-8">
<script src="main.js"></script>
</head>
<body>
<div>
<input type="number" id="day" autocomplete="off">
<select id="month">
<option>January</option>
<option>February</option>
<option>March</option>
<option>April</option>
<option>May</option>
<option>June</option>
<option>July</option>
<option>August</option>
<option>September</option>
<option>October</option>
<option>November</option>
<option>December</option>
</select>
<input type="number" id="year" autocomplete="off">
</div>
<input type="button" id="date-button" value="Count">
<div id="result" >
</div>
</body>
</html>
Javascript:
let gram_start, difference;
const one_day = 24*60*60*1000;
let months_list = {
"January": [1,31],
"February": [2,28],
"March": [3,31],
"April": [4,30],
"May": [5,31],
"June": [6,30],
"July": [7,31],
"August": [8,31],
"September": [9,30],
"October": [10,31],
"November": [11,30],
"December": [12,31]
};
let month_index = Object.keys(months_list);
function leapyear(year) {
return (year % 100 === 0 ? year % 400 === 0 : year % 4 === 0);
}
window.onload = function count() {
document.getElementById("date-button").addEventListener("click", () => {
let years_write = 0;
let months_write = 0;
let day = parseInt(document.getElementById("day").value);
let month = document.getElementById("month").value;
let year = parseInt(document.getElementById("year").value);
let month_obj = months_list[month];
let target_date = new Date(year, month_obj[0]-1, day);
let today_date = new Date();
let matcher = new Date(today_date.getFullYear(),today_date.getMonth(), today_date.getDate());
//this works fine
if(target_date > today_date) {
gram_start = "There are that many days left to this date: <br>";
difference = Math.ceil((target_date - today_date) / one_day);
}
else if(target_date < today_date) {
gram_start = "There has been that many days since that date: <br>";
difference = Math.round((today_date - target_date) / one_day);
}
if(target_date < matcher)
difference--;
let remaining_days = difference;
if(target_date > today_date) {
while(remaining_days >= (leapyear(year) ? 366 : 365)) {
remaining_days -= leapyear(year) ? 366 : 365;
years_write++;
year--;
}}
else if(target_date < today_date) {
while(remaining_days >= (leapyear(year) ? 366 : 365)) {
remaining_days -= leapyear(year) ? 366 : 365;
years_write++;
year++;
}}
if(leapyear(year))
months_list.Luty[1] = 29;
else
months_list.Luty[1] = 28;
let i = month_obj[0]-1;
if(target_date > today_date) {
while(remaining_days >= (months_list[month_index[i]][1])) {
remaining_days -= (months_list[month_index[i]][1]);
months_write++;
i--;
}}
else if(target_date < today_date) {
while(remaining_days >= months_list[month_index[i]][1]) {
remaining_days -= months_list[month_index[i]][1];
months_write++;
i++;
}}
document.getElementById("result").innerHTML = gram_start + difference + " days, so:" + years_write + " years, " + months_write + " months and " + remaining_days + " days.";
})};

Trying to compare value of string that are programmatically added with javascript

I'm trying to prevent my laps from counting the same second. So I'm trying to take the current value and evaluate it as != not equal to the previous value before appending it.
Here is the function, and my HTML. Not sure if I can do anything with the ids I set up. I have jquery set up to run in my javascript, so if you have any ideas with that I would be open to listening. There are a couple of things that probably don't have a use that I have not removed yet.
Javascript Function
let seconds = 0;
let minutes = null;
let hours = null;
let startTimer = null;
let time = null;
let isRunning = (false);
let lapContainer = [];
let x;
let outputseconds;
let outputminutes;
let outputhours;
//connection to button
document.getElementById("start").addEventListener("click", start);
document.getElementById("stop").addEventListener("click", stop);
document.getElementById("reset").addEventListener("click", reset);
document.getElementById("lap").addEventListener("click", lap);
document.getElementById("resetLaps").addEventListener("click", resetLaps);
//functions
function start() {
if (isRunning === false) {
isRunning = true;
//interval
startTimer = setInterval(function () {
seconds++;
if (seconds <= 9) {
outputseconds = "0" + seconds;
document.getElementById("seconds").innerHTML = outputseconds;
} else if (seconds <= 60) {
outputseconds = seconds;
document.getElementById("seconds").innerHTML = outputseconds;
} else if (seconds >= 60) {
minutes++;
outputseconds = "00";
outputminutes = "0" + minutes;
document.getElementById("seconds").innerHTML = outputseconds;
document.getElementById("minutes").innerHTML = outputminutes;
seconds = 0;
} else if (minutes >= 9) {
outputminutes = minutes;
document.getElementById("minutes").innerHTML = outputminutes;
} else if (minutes >= 60) {
hours++;
outputminutes = "00";
outputhours = "0" + hours;
document.getElementById("minutes").innerHTML = outputminutes;
document.getElementById("hours").innerHTML = outputhours;
minutes = 0;
} else if (hours > 9) {
outputhours = hours;
document.getElementById("hours").innerHTML = outputhours;
}
}, 1000); //end of interval
} // end of if check
// should this be seperated out as a function???
let startTime = "00";
if (outputseconds > 0) {
if (outputminutes > 0) {
if (outputhours > 0) {
return outputhours + ":" + outputminutes + ":" + outputseconds;
} else {
return startTime + ":" + outputminutes + ":" + outputseconds;
} // hours
} else {
return startTime + ":" + startTime + ":" + outputseconds;
} //minutes
} else {
return startTime + ":" + startTime + ":" + startTime;
} // end of nested if seconds
} //end of start function
function stop() {
clearInterval(startTimer);
isRunning = false;
}
function reset() {
clearInterval(startTimer);
document.getElementById("seconds").innerHTML = "00";
document.getElementById("minutes").innerHTML = "00";
document.getElementById("hours").innerHTML = "00";
seconds = 0;
minutes = 0;
hours = 0;
isRunning = false;
}
function lap() {
if (isRunning === true) {
//initialize time
let lapTime = start();
//create connection to div
lapContainer = document.getElementById("lapContainer");
// how to check if they equal each other
//create element
const para = document.createElement("p");
//how many laps have been created
let i = document.getElementById("lapContainer").childElementCount;
let index = [i];
//create an index that will add an id to paragraph
para.id = index;
//add the lap to text
para.innerText = lapTime;
let laps = [];
laps = document.getElementById("lapContainer").childNodes[1].textContent;
let lastItem = laps[laps.length - 1];
let currentItem = laps[laps.length];
document.getElementById("test").innerHTML = laps;
if (currentItem !== lastItem) {
lapContainer.appendChild(para);
}
}
}
function resetLaps() {
$(lapContainer).empty();
isRunning = false;
}
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Stopwatch</title>
<meta name="description" content="A simple stopwatch application" />
<meta name="author" content="****" />
<link rel="icon" href="/favicon.ico" />
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<link rel="stylesheet" href="./css/styles.css" />
</head>
<body>
<!-- your content here... -->
<div class="menu">
Timer
Alarm
</div>
<div class="stopwatch-container">
<div class="stopwatch-wrapper">
<div class="stopwatch-button-container">
<button type="button" id="start">START</button>
<button type="button" id="stop">STOP</button>
<button type="button" id="reset">RESET</button>
<button type="button" id="lap">LAP</button>
<button type="button" id="resetLaps">RESET LAPS</button>
</div>
<div class="rectangle-container">
<div class="rectangle">
<p id="textWrapper">
<span id="hours">00</span>:<span id="minutes">00</span>:<span
id="seconds"
>00</span
>
</p>
</div>
</div>
</div>
</div>
<div class="lineBreak"></div>
<div id="lapContainer" class="lap-container"></div>
<p id="test"></p>
<script src="./scripts/scripts.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</body>
</html>
Few things you might need to do:
1.When you set the laps array you need to get the array of texts of the all nodes, not just a text of the first node:
//laps = document.getElementById("lapContainer").childNodes[1].textContent;
laps = Array.from(document.getElementById("lapContainer").childNodes).map(node => node.textContent);
2.When you set currentItem you can not use laps[laps.length] because your new value not in the array yet and so it will return undefined. Instead you can just use your lapTime value:
let lastItem = laps[laps.length - 1];
//let currentItem = laps[laps.length];
let currentItem = lapTime;
Example:
let isRunning = Boolean(true);
let lapContainer = [];
document.querySelector('#lap').addEventListener('click', () => lap());
function lap() {
if (isRunning === true) {
//initialize time
let lapTime = start();
//create connection to div
lapContainer = document.getElementById("lapContainer");
// how to check if they equal each other
//create element
const para = document.createElement("p");
//how many laps have been created
let i = document.getElementById("lapContainer").childElementCount;
let index = [i];
//create an index that will add an id to paragraph
para.id = index;
//add the lap to text
para.innerText = lapTime;
let laps = [];
//laps = document.getElementById("lapContainer").childNodes[1].textContent;
laps = Array.from(document.getElementById("lapContainer").childNodes).map(node => node.textContent);
let lastItem = laps[laps.length - 1];
//let currentItem = laps[laps.length];
let currentItem = lapTime;
document.getElementById("test").innerHTML = laps;
if (currentItem !== lastItem) {
lapContainer.appendChild(para);
}
}
}
const start = () => new Date().toString();
<body>
<!-- your content here... -->
<div class="menu">
Timer
Alarm
</div>
<div class="stopwatch-container">
<div class="stopwatch-wrapper">
<div class="stopwatch-button-container">
<button type="button" id="start">START</button>
<button type="button" id="stop">STOP</button>
<button type="button" id="reset">RESET</button>
<button type="button" id="lap">LAP</button>
<button type="button" id="resetLaps">RESET LAPS</button>
</div>
<div class="rectangle-container">
<div class="rectangle">
<p id="textWrapper">
<span id="hours">00</span>:<span id="minutes">00</span>:<span
id="seconds"
>00</span
>
</p>
</div>
</div>
</div>
</div>
<div class="lineBreak"></div>
<div id="lapContainer" class="lap-container"></div>
<p id="test"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</body>

how to display " backward timer " using JavaScript?

I have my DOM like this :
<input type="number" id="input" value="" placeholder="Enter time in minutes">
<button id="button">Go</button>
<button id="reset">reset</button>
<div class="timer">
<div class="mint" id="mint"></div>
<div class="sec" id="sec"></div>
</div>
And my JavaScript Like this :
let currentTime = 0;
let intervalClear;
let input = document.getElementById('input');
let button = document.getElementById('button')
button.addEventListener('click', ()=>{
let value = input.value * 60000;
function getTime(){
currentTime++
function backcount(currentTime){
let output = value - currentTime
console.log(output);
const mint = document.getElementById('mint'),
sec = document.getElementById('sec');
let minute = Math.floor(output/60000)
let second = ((output % 60000) / 1000).toFixed(0)
mint.innerText = minute;
sec.innerText = second;
if(output == 0){
clearInterval(intervalClear)
}
}
backcount(currentTime);
}
getTime()
intervalClear = setInterval(getTime, 1000)
})
const reset = document.getElementById('reset')
reset.addEventListener('click', ()=>{
clearInterval(intervalClear);
input.value = '';
})
now I want to display value in my web page But it doesn't updating. seems like its freezes. but my "setInterval()" running properly.
How can I resolve this issue? need help!
You need instead of this code
let output = value - currentTime
use this
let output = value - (currentTime * 1000)
let currentTime = 0;
let intervalClear;
let input = document.getElementById('input');
let button = document.getElementById('button')
button.addEventListener('click', ()=>{
let value = input.value * 60000;
function getTime(){
currentTime++
function backcount(currentTime){
let output = value - (currentTime * 1000)
console.log(output);
const mint = document.getElementById('mint'),
sec = document.getElementById('sec');
let minute = Math.floor(output/60000)
let second = ((output % 60000) / 1000).toFixed(0)
mint.innerText = minute;
sec.innerText = second;
if(output == 0){
clearInterval(intervalClear)
}
}
backcount(currentTime);
}
getTime()
intervalClear = setInterval(getTime, 1000)
})
const reset = document.getElementById('reset')
reset.addEventListener('click', ()=>{
clearInterval(intervalClear);
input.value = '';
})
<input type="number" id="input" value="" placeholder="Enter time in minutes">
<button id="button">Go</button>
<button id="reset">reset</button>
<div class="timer">
<div class="mint" id="mint"></div>
<div class="sec" id="sec"></div>
</div>
Based on #Oleg Barabanov's answer I found one bug. If you didn't enter any value in text box or first added value then click on "Reset" and click on "Go" button then counter started with negative value. I fixed that issue with this code.
Script
var intervalClear;
var input = document.querySelector('#input');
var mint = document.querySelector('#mint');
var sec = document.querySelector('#sec');
var go_button = document.querySelector('#button');
var reset_button = document.querySelector('#reset');
go_button?.addEventListener('click', () => {
if (input.value != '' && input.value != 0 && parseInt(input.value) != NaN) {
startTimer(input.value, mint, sec);
}
});
reset_button?.addEventListener('click', () => {
clearInterval(intervalClear);
mint.textContent = '00';
sec.textContent = '00';
});
function startTimer(duration, minElement, secElement) {
clearInterval(intervalClear);
var timer = duration * 60, minutes, seconds;
intervalClear = setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
minElement.textContent = minutes;
secElement.textContent = seconds;
if (--timer < 0) {
timer = duration;
}
if (minutes == 0 && seconds == 0) {
clearInterval(intervalClear);
mint.textContent = '00';
sec.textContent = '00';
}
}, 1000);
}
DOM
<input type="number" id="input" placeholder="Enter time in minutes" >
<button id="button">Go</button>
<button id="reset">reset</button>
<div class="timer">
<div class="mint" id="mint">00</div>
<div class="sec" id="sec">00</div>
</div>

select all checkboxes at a particular time in html or js

I am in need of having a3 checkboxes that should have a tick mark from 2 pm till 11 pm IST in javascript or HTML. This is what I tried
<html>
<body>
<center>
<span style="margin-left:50px; margin-top:0px;">
<p align="left"><font color="white"> <b> India Time: 2pm to 11pm IST </b>
</br>
<input type="checkbox" id="user1" name="user1" value="user1" > User1<br>
<input type="checkbox" id="user2" name="user2" value="user2" > User2<br>
<input type="checkbox" id="user3" name="user3" value="user3" > User3<br>
</p>
<img border="1" src="https://i.postimg.cc/VkPzvHCJ/gh.png" style=" margin-top:-129px;" >
</span>
<h3 style= "font-family: "Gotham A","Gotham B",sans-serif;>
<br> <p align="center" style=" margin-top:-30px;"> <font color="#339933"> <b>RStudio Dashboard
</h3></P>
</body>
<script>
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm}
var today = dd+'/'+mm+'/'+yyyy;
var holidays = [];
holidays = ["01/01/2019" , "26/01/2019" , "20/02/2019" , "01/05/2019" , "27/05/2019" , "04/06/2019", "04/07/2019" , "15/08/2019" , "02/09/2019" , "10/09/2019" , "02/10/2019" , "28/11/2019" , "25/12/2019"];
//var n = str.indexOf("welcome");
if {
var startTime = '2:00 PM';
var endTime = '11:00 PM';
var curr_time = getval();
//var curr_time = '12:39 AM';
//alert(curr_time);
if (get24Hr(curr_time) > get24Hr(startTime) && get24Hr(curr_time) < get24Hr(endTime)) {
//in between these two times
//alert("Yes")
document.getElementById("sid").checked = true;
document.getElementById("anil").checked = true;
document.getElementById("vin").checked = true;
} else {
//document.getElementById("user1").checked = true;
//document.getElementById("user2").checked = true;
}
function get24Hr(time){
var hours = Number(time.match(/^(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if(AMPM == "PM" && hours<12) hours = hours+12;
if(AMPM == "AM" && hours==12) hours = hours-12;
var minutes = Number(time.match(/:(\d+)/)[1]);
hours = hours*100+minutes;
console.log(time +" - "+hours);
return hours;
}
function getval() {
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10) minutes = "0" + minutes;
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
var current_time = hours + ":" + minutes + " " + suffix;
return current_time;
}
}
else
{
print ("hello")
}
</script>
</html>
This is what I tried. The code is working, but it seems a bit complicated. Is there any simple method?
The only requirement is to tick the checkboxes from 2 pm to 11 pm IST
Add this js function. And then add "onClick" on every Input. Also the name must be the same.
<script language="JavaScript">
function toggle(source) {
checkboxes = document.getElementsByName('user');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
<input type="checkbox" onClick="toggle(this)" id="user1" name="user" value="user1" > User1<br>
<input type="checkbox" onClick="toggle(this)" id="user2" name="user" value="user2" > User2<br>
<input type="checkbox" onClick="toggle(this)" id="user3" name="user" value="user3" > User3<br>

JavaScript stopwatch (Cannot set property 'innerHTML' of null error)

I've been trying to add a simple stopwatch to my Rails app, and I've adapted the one I found here: https://jsfiddle.net/waqasumer/agru2bdL/
The code seems to work in the console (the timer starts and stops), but I'm getting this error when using the controls and the UI is not showing the stopwatch (it's just reading zero):
Uncaught TypeError: Cannot set property 'innerHTML' of null
Any help to get this working would be appreciated. I've included my code below.
var min = 0;
var sec = 0;
var msec = 0;
var getMin = document.getElementById("min");
var getSec = document.getElementById("sec");
var getmsec = document.getElementById("msec");
var interval;
function timer() {
msec++
getmsec.innerHTML = msec;
if (msec >= 100) {
sec++;
if (sec <= 9) {
getSec.innerHTML = "0" + sec;
} else {
getSec.innerHTML = sec;
}
msec = 0;
} else if (sec >= 60) {
min++;
if (min <= 9) {
getMin.innerHTML = "0" + min;
} else {
getMin.innerHTML = min;
}
sec = 0;
}
}
function start() {
interval = setInterval(timer, 10);
var btn = document.getElementById("start");
btn.disabled = true;
}
function stop() {
clearInterval(interval);
var btn = document.getElementById("start");
btn.disabled = false;
}
function reset() {
min = "00";
sec = "00";
msec = "00";
getMin.innerHTML = min;
getSec.innerHTML = sec;
getmsec.innerHTML = msec;
clearInterval(interval);
}
function lapTimer() {
var Laps = document.getElementById('laps');
Laps.innerHTML += "<div>" + " " + getMin.innerHTML + ":" + getSec.innerHTML + ":" + getmsec.innerHTML + "</div>";
}
<h1 class="title">Stopwatch</h1>
<div class="stopwatch">
<div class="circle">
<div class="time"><span id="min">00</span>:<span id="sec">00</span>:<span id="msec">00</span></div>
</div>
<div class="controls">
<button id="start" onclick="start()" type="button"><img class="controls-img" id="playButton" src="<%= asset_path( 'play_button.png' ) %>" /></button>
<button onclick="stop()" type="button"><img class="controls-img" id="pauseButton" src="<%= asset_path( 'pause_button.png' ) %>" /></button>
<button onclick="lapTimer()" id="lapButton" type="button"><img class="controls-img" id="pauseButton" src="<%= asset_path( 'lap.png' ) %>" /></button>
<button onclick="reset()" type="button"><img class="controls-img" id="pauseButton" src="<%= asset_path( 'reset_button.png' ) %>" />
</button>
</div>
</div>
<br>
<div class="row" id="laps"></div>
The js code will executed, before the page is ready. You have 2 solutions. Put your js code at the end of the page or look here $(document).ready equivalent without jQuery

Categories