The element will not take a textContent input - javascript

When I click the date value I'm having this error: Uncaught TypeError: Cannot read property 'textContent' of undefined
This is my code can you help me in determining the source of the error and how can I correct this?
function Timer(elem) {
var time = 3000;
var interval;
var offset;
function update() {`enter code here`
time += delta();
var formattedTime = timeFormatter(time);
elem.textContent = formattedTime;
}
function delta() {
var now = Date.now();
var timePassed = now - offset;
offset = now;
return timePassed;
}
function timeFormatter(timeInMilliseconds) {
var time = new Date(timeInMilliseconds)
var minutes = time.getMinutes().toString();
var seconds = time.getSeconds().toString();
if (minutes.length < 2) {
minutes = '0' + minutes;
}
if (seconds.length < 2) {
seconds = '0' + seconds;
}
return minutes + ' : ' + seconds;
}
this.isOn = false;
this.start = function() {};
if (!this.isOn) {
interval = setInterval(update, 10);
offset = Date.now();
this.isOn = true;
}
};
this.stop = function() {
if (this.isOn) {
clearInterval(interval);
interval = nul;
this.isOn = false;
}
};
this.reset = function() {};

Edited version for the other errors.
function Timer(elem) {
var time= 0;
var offset;
var interval;
function update() {
if (this.isOn) {
time += delta();
var formattedTime = timeFormatter(time);
}
elem.textContent = formattedTime;
}
function delta() {
var now = Date.now();
var timePassed = now - offset;
offset = "5:00";
return timePassed;
}
function timeFormatter(time) {
time = new Date(time);
var minutes = time.getMinutes().toString();
var seconds = time.getSeconds().toString();
if (minutes.length < 2) {
minutes = '0' + minutes;
}
if (seconds.length < 2) {
seconds = '0' + seconds;
}
return minutes + ' : ' + seconds;
}
this.start = function() {
interval = setInterval(update.bind(this), 10);
time++;
this.isOn = true;
};
this.stop = function() {
clearInterval(interval)
interval = null;
this.isOn = false;
};
this.reset = function() {
time= 300;
update();
};
this.isOn = false;
}

Related

Continue timer in MVC after reload page

I'm trying to implement a timer that upon page reload it doesn't resets. I've thought about the ways to do it (model, viewdata, session, etc.) and I think the cookie method is the one that will work best. However I'm running into logical issues with the implementation and don't know how to go forward.
Here are the files:
CSHTML
<div class="mb-3">
<p class="mb-4 bold-txt">#Model.Email</p>
<span class="block" id="countdown-timer"> #localization.GetLocalization("Zenegy_Auth_Email_Verification_Enter_Code"): <span id="ten-countdown"></span></span>
<span class="block" id="code-expired-text" style="display:none"> #localization.GetLocalization("Zenegy_Auth_Email_Verification_Code_Expired")</span>
</div>
.
.
.
<script>
otpInput.initInputs(#(ViewBag.HasError != null && ViewBag.HasError ? "true" : "false"))
console.log(#http.HttpContext.Request.Cookies["time-left"])
countdown("ten-countdown", 5, 0, true, #http.HttpContext.Request.Cookies["time-left"]);
</script>
COUNTDOWN.JS
let countdown = (elementName, minutes, seconds, isResendCodeForm, timeLeft) => {
let element, endTime, hours, mins, msLeft, time, timeLeft;
let twoDigits = (n) => {
return n <= 9 ? "0" + n : n;
};
let updateTimer = () => {
msLeft = endTime - +new Date();
document.cookie = "time-left=" + msLeft;
msLeft = timeLeft;
if (msLeft < 1000) {
if (isResendCodeForm) {
toggleTimerExpired();
}
else {
document.getElementById('ten-countdown').style.display = "none";
document.getElementById('timer-expired-text').style.display = "inline";
}
} else {
time = new Date(msLeft);
hours = time.getUTCHours();
mins = time.getUTCMinutes();
element.innerHTML =
(hours ? hours + ":" + twoDigits(mins) : mins) +
":" +
twoDigits(time.getUTCSeconds()) +
" min";
setTimeout(updateTimer, time.getUTCMilliseconds() + 500);
}
};
element = document.getElementById(elementName);
endTime = +new Date() + 1000 * (60 * minutes + seconds) + 500;
updateTimer();
};
let syncTimer = (timeLeft) => {
msLeft = timeLeft;
}
function toggleTimerExpired() {
document.getElementById('resend-form').style.display = "block";
document.getElementById('code-expired-text').style.display = "block";
document.getElementById('countdown-timer').style.display = "none";
document.getElementById('resend-code-text').style.display = "none";
document.getElementById('verification-code-form').style.display = "none";
}
CONTROLLER
[HttpPost("validateemailcode"), ValidateAntiForgeryToken, UserVerifyAuthorize]
public async Task<ActionResult> ValidateEmailVerificationCode(VerifyUserEmailZenegyViewModel model)
{
var timeLeft = HttpContext.Request.Cookies["time-left"];
if (!ModelState.IsValid)
{
var verifyUserMailViewModel = new VerifyUserEmailZenegyViewModel
{
Email = model.Email
};
CreateErrorNotification("Invalid_Request");
return View("~/Views/AuthZenegy/VerifyUserEmail.cshtml", verifyUserMailViewModel);
}
try
{
await _accountService.ValidateEmailVerificationCodeAsync(model.Email, model.ConcatenatedVerificationCode);
await SignOutAsync();
await SignInAsync(await _authProvider.RefreshLoginAsync(), false);
ViewBag.Header = EmailCodeVerificationSuccessHeaderText;
ViewBag.SubHeader = EmailCodeVerificationSuccessSubHeaderText;
ViewBag.Action = EmailCodeVerificationSuccessAction;
return View("~/Views/AuthZenegy/VerificationSuccess.cshtml");
}
catch (NotAcceptableException)
{
ViewBag.HasError = true;
CreateErrorNotification("VerifyUser_MustSpecify_MailOrPhone_AndCode");
return VerifyEmailView(model);
}
catch (NotFoundException)
{
ViewBag.HasError = true;
CreateErrorNotification("VerifyUser_UserNotFound");
return VerifyEmailView(model);
}
catch (AlreadyExistsException)
{
ViewBag.HasError = true;
CreateErrorNotification("VerifyUser_AlreadyExists_EmailOrMail");
return VerifyEmailView(model);
}
catch (ValidationException)
{
HttpContext.Response.Cookies.Append("time-left", timeLeft);
ViewBag.HasError = true;
CreateErrorNotification("VerifyUser_Invalid_VerificationCode");
return VerifyEmailView(model);
}
catch (Exception)
{
ViewBag.HasError = true;
return VerifyEmailView(model);
}
}
Anyone have any idea what should I do?

Alert returning as undefined

I am trying to have my alert show up with the time that my timer shows.
function Stopwatch(elem) {
var time = 0;
var offset;
var interval;
function update() {
if (this.isOn) {
time += delta();
}
elem.textContent = timeFormatter(time);
}
function delta() {
var now = Date.now();
var timePassed = now - offset;
offset = now;
return timePassed;
}
function timeFormatter(time) {
time = new Date(time);
var minutes = time.getMinutes().toString();
var seconds = time.getSeconds().toString();
var milliseconds = time.getMilliseconds().toString();
if (minutes.length < 2) {
minutes = '0' + minutes;
}
if (seconds.length < 2) {
seconds = '0' + seconds;
}
while (milliseconds.length < 3) {
milliseconds = '0' + milliseconds;
}
return minutes + ' : ' + seconds + ' . ' + milliseconds;
}
this.start = function() {
interval = setInterval(update.bind(this), 10);
offset = Date.now();
this.isOn = true;
};
this.stop = function() {
clearInterval(interval);
interval = null;
this.isOn = false;
};
this.reset = function() {
time = 0;
update();
};
this.isOn = false;
}
var timer = document.getElementById('timer');
var toggleBtn = document.getElementById('toggle');
var resetBtn = document.getElementById('reset');
var watch = new Stopwatch(timer);
function start() {
toggleBtn.textContent = 'Stop';
watch.start();
}
function stop() {
toggleBtn.textContent = 'Start';
watch.stop();
}
toggleBtn.addEventListener('click', function() {
watch.isOn ? stop() : start();
});
resetBtn.addEventListener('click', function() {
watch.reset();
});
function alertSystem(){
var timer = document.getElementById('timer')
alert(timer);
}
<h1 id="timer">00 : 00 . 000</h1>
<div>
<button class=button id="toggle">Start</button>
<button class=button id="reset">Reset</button>
<button onclick='alertSystem()'>get number</button>
</div>
It's a lot of code, but it is mostly to get the timer working. The last function called alertSystem() is on the bottom and is the one that triggers the alert call. For me the alert shows up as [object HTMLHeadingElement] or as undefined. The former comes up when I have alert(timer); but if I do alert(timer.value); or alert(timer.length); I get the latter.
Does anyone know how I can just get the value of the timer in the alert?
To get the timer's value, you should do something like:
document.querySelector('#timer').innerHTML
Otherwise , document.getElementById returns a full element as a js object.

localStorage how to save countdown value so it wont reset when I reload the page

When I reload the page, my 1 minute countdown also reloads.
I tried to use localStorage but it seems to me failed.
Please have a look, I do not know where I should fix.
Thank you
My script
/* for countdown */
var countDown = (function ($) {
// Length ms
var timeOut = 10000;
// Interval ms
var timeGap = 1000;
var currentTime = (new Date()).getTime();
var endTime = (new Date()).getTime() + timeOut;
var guiTimer = $("#clock");
var running = true;
var timeOutAlert = $("#timeout-alert");
timeOutAlert.hide();
var updateTimer = function() {
// Run till timeout
if(currentTime + timeGap < endTime) {
setTimeout( updateTimer, timeGap );
}
// Countdown if running
if(running) {
currentTime += timeGap;
if(currentTime >= endTime) { // if its over
guiTimer.css("color","red");
}
}
// Update Gui
var time = new Date();
time.setTime(endTime - currentTime);
var minutes = time.getMinutes();
var seconds = time.getSeconds();
guiTimer.html((minutes < 10 ? '0' : '') + minutes + ':' + (seconds < 10 ? '0' : '') + seconds);
if (parseInt(guiTimer.html().substr(3)) <= 10){ // alert the user that he is running out of time
guiTimer.css('color','red');
timeOutAlert.show();
}
};
var pause = function() {
running = false;
};
var resume = function() {
running = true;
};
var start = function(timeout) {
timeOut = timeout;
currentTime = (new Date()).getTime();
endTime = (new Date()).getTime() + timeOut;
updateTimer();
};
return {
pause: pause,
resume: resume,
start: start
};
})(jQuery);
jQuery('#break').on('click',countDown.pause);
jQuery('#continue').on('click',countDown.resume);
var seconds = 60; // seconds we want to count down
countDown.start(seconds*1000);
I tried to fix it but I dont know where/how to put localStorage.
This may help you.
HTML Code:
<div id="divCounter"></div>
JS Code
var test = 60;
if (localStorage.getItem("counter")) {
if (localStorage.getItem("counter") <= 0) {
var value = test;
alert(value);
} else {
var value = localStorage.getItem("counter");
}
} else {
var value = test;
}
document.getElementById('divCounter').innerHTML = value;
var counter = function() {
if (value <= 0) {
localStorage.setItem("counter", test);
value = test;
} else {
value = parseInt(value) - 1;
localStorage.setItem("counter", value);
}
document.getElementById('divCounter').innerHTML = value;
};
var interval = setInterval(function() { counter(); }, 1000);

Pomodoro Clock's time doesn't work

I am currently working on Pomodoro Clock project, everything seems working on plus/minus buttons in both Session and Break but time itself is not working (in blue circle area), something is little missing, please see below.
var time = document.querySelector(".time");
var timerBody = document.querySelector(".timerBody");
var currentWork = document.querySelector(".currentWork");
var sessionLength = document.querySelector(".sessionLength");
var minusSessionLength = document.querySelector(".minus-sessionLength");
var plusSessionLength = document.querySelector(".plus-sessionLength");
var breakLength = document.querySelector(".breakLength");
var minusBreakLength = document.querySelector(".minus-breakLength");
var plusBreakLength = document.querySelector(".plus-breakLength");
var isLoop = false;
var isSession = true;
var Sound = new Audio('http://www.oringz.com/oringz-uploads/sounds-917-communication-channel.mp3');
function GetTime(timeString){
timeString = timeString.split(':');
var seconds = parseInt(timeString[0]) * 60 + parseInt(timeString[1]);
return seconds;
}
// Errors here
function setTime(seconds) {
var timeString = [];
timeString.push(Math.floor(seconds/60));
timeString.push((seconds % 60 < 10) ? '0' + (seconds % 60).toString() : (seconds % 60));
return timeString.join(':')
}
var currentTime = GetTime(time.innerHTML);
minusSessionLength.addEventListener('click', function(event){
if(!isLoop) {
var STime = parseInt(sessionLength.innerHTML);
if(STime - 1 >= 1)
STime--;
sessionLength.innerHTML = STime;
if(isSession) {
time.innerHTML = STime + ':00';
currentTime = GetTime(time.innerHTML);
}
}
});
plusSessionLength.addEventListener('click', function(event){
if(!isLoop) {
var STime = parseInt(sessionLength.innerHTML);
sessionLength.innerHTML = ++STime;
if(isSession){
time.innerHTML = STime + ':00';
currentTime = GetTime(time.innerHTML);
}
}
});
minusBreakLength.addEventListener('click', function(event){
if(!isLoop) {
var BTime = parseInt(breakLength.innerHTML);
if(BTime - 1 >= 1) {
BTime--;
breakLength.innerHTML = BTime;
}
if(!isSession) {
time.innerHTML = BTime + ':00';
currentTime = GetTime(time.innerHTML);
}
}
});
plusBreakLength.addEventListener('click', function(event){
if(!isLoop) {
var BTime = parseInt(breakLength.innerHTML);
breakLength.innerHTML = ++BTime;
if(!isSession) {
time.innerHTML = BTime + ':00';
currentTime = GetTime(time.innerHTML);
}
}
});
var loop;
timerBody.addEventListener('click', function(event){
if(isLoop) {
clearInterval(loop);
currentWork.innerHTML = 'Paused';
isLoop = !isLoop;
}
else {
currentWork.innerHTML = isSession ? 'Session' : 'Break';
loop = setInterval(function() {
time.innerHTML = SetTime(--currentTime);
if(currentTime < 1) {
if(isSession) {
currentWork.innerHTML = 'Break';
time.innerHTML = breakLength.innerHTML + ':00';
currentTime = GetTime(time.innerHTML);
timerBody.style.borderColor = "#80FF80";
Sound.play();
var isBreakTitle = true;
var changeTitle = setInterval(function(){
document.title = isBreakTitle ? '***Break!***' : '************';
isBreakTitle = !isBreakTitle;
}, 100);
setTimeout(function() {
clearInterval(changeTitle);
document.title = 'Pomodoro clock';
}, 5000);
isSession = !isSession;
}
else {
currentWork.innerHTML = 'Session';
time.innerHTML = sessionLength.innerHTML + ':00';
currentTime = GetTime(time.innerHTML);
timerBody.style.borderColor = "#F64141";
Sound.play();
var isSessionTitle = false;
var changeTitle = setInterval(function() {
document.title = isSessionTitle ? '***Session!****' : '************';
isSessionTitle = !isSessionTitle;
}, 100);
setTimeout(function() {
clearInterval(changeTitle);
document.title = 'Pomodoro clock';
}, 5000);
isSession = !isSession;
}
}
}, 1000);
isLoop = !isLoop;
}
});
Here's mispelling mistake which should be "SetTime"
function SetTime(seconds) {
var timeString = [];
timeString.push(Math.floor(seconds/60));
timeString.push((seconds % 60 < 10) ? '0' + (seconds % 60).toString() : (seconds % 60));
return timeString.join(':')
}
Hope that helps to your future issues.

Java Script Calculating and Displaying Idle Time

I'm trying to write with javascript and html how to display the time a user is idle (not moving mouse or pressing keys). While the program can detect mousemovements and key presses, the program for some reason isn't calling the idleTime() method which displays the time in minutes and seconds.
I'm wondering why the method isn't getting called, as if it is called it would display true or false if a button is pressed.
var startIdle = new Date().getTime();
var mouseMoved = false;
var buttonPressed = false;
function idleTime() {
document.write(buttonPressed);
if (mouseMoved || buttonPressed) {
startIdle = new Date().getTime();
}
document.getElementById('idle').innerHTML = calculateMin(startIdle) + " minutes: " + calculateSec(startIdle) + " seconds";
var t = setTimeout(function() {
idleTime()
}, 500);
}
function calculateSec(startIdle1) {
var currentIdle = new Date().getTime();
var timeDiff = Math.abs(currentIdle - startIdle1);
var idleSec = Math.ceil(timeDiff / (1000));
return idleSec % 60;
}
function calculateMin(startIdle1) {
var currentIdle = new Date().getTime();
var timeDiff = Math.abs(currentIdle - startIdle1);
var idleMin = Math.ceil(timeDiff / (1000 * 60));
return idleMin;
}
var timer;
// mousemove code
var stoppedElement = document.getElementById("stopped");
function mouseStopped() { // the actual function that is called
mouseMoved = false;
stoppedElement.innerHTML = "Mouse stopped";
}
window.addEventListener("mousemove", function() {
mouseMoved = true;
stoppedElement.innerHTML = "Mouse moving";
clearTimeout(timer);
timer = setTimeout(mouseStopped, 300);
});
//keypress code
var keysElement = document.getElementById('keyPressed');
window.addEventListener("keyup", function() {
buttonPressed = false;
keysElement.innerHTML = "Keys not Pressed";
clearTimeout(timer);
timer = setTimeout("keysPressed", 300);
});
window.addEventListener("keydown", function() {
buttonPressed = true;
keysElement.innerHTML = "Keys Pressed";
clearTimeout(timer);
timer = setTimeout("keyPressed", 300);
});
function checkTime(i) {
if (i < 10) {
i = "0" + i
}; // add zero in front of numbers < 10
return i;
}
Here is the HTML code:
<body onload="idleTime()">
<div id="stopped"><br>Mouse stopped</br></div>
<div id="keyPressed"> Keys not Pressed</div>
<strong>
<div id="header"><br>Time Idle:</br>
</div>
<div id="idle"></div>
</strong>
</body>
Actually the keysElement and stoppedElement were not referred firing before the DOM load. and also removed the document.write
Thats all all good. :)
var startIdle = new Date().getTime();
var mouseMoved = false;
var buttonPressed = false;
function idleTime() {
//document.write(buttonPressed);
if (mouseMoved || buttonPressed) {
startIdle = new Date().getTime();
}
document.getElementById('idle').innerHTML = calculateMin(startIdle) + " minutes: " + calculateSec(startIdle) + " seconds";
var t = setTimeout(function() {
idleTime()
}, 500);
}
function calculateSec(startIdle1) {
var currentIdle = new Date().getTime();
var timeDiff = Math.abs(currentIdle - startIdle1);
var idleSec = Math.ceil(timeDiff / (1000));
return idleSec % 60;
}
function calculateMin(startIdle1) {
var currentIdle = new Date().getTime();
var timeDiff = Math.abs(currentIdle - startIdle1);
var idleMin = Math.ceil(timeDiff / (1000 * 60));
return idleMin;
}
var timer;
// mousemove code
//var stoppedElement = document.getElementById("stopped");
function mouseStopped() { // the actual function that is called
mouseMoved = false;
document.getElementById("stopped").innerHTML = "Mouse stopped";
}
function keyStopped() { // the actual function that is called
buttonPressed = false;
document.getElementById("keyPressed").innerHTML = "Keys stopped";
}
window.addEventListener("mousemove", function() {
mouseMoved = true;
document.getElementById("stopped").innerHTML = "Mouse moving";
clearTimeout(timer);
timer = setTimeout(mouseStopped, 500);
});
window.addEventListener("keyup", function() {
buttonPressed = true;
document.getElementById('keyPressed').innerHTML = "Keys Pressed";
clearTimeout(timer);
timer = setTimeout(keyStopped, 500);
});
window.addEventListener("keydown", function() {
buttonPressed = true;
document.getElementById('keyPressed').innerHTML = "Keys Pressed";
clearTimeout(timer);
timer = setTimeout(keyStopped, 500);
});
function checkTime(i) {
if (i < 10) {
i = "0" + i
}; // add zero in front of numbers < 10
return i;
}
window.onload = idleTime;
<div id="stopped"><br>Mouse stopped</br></div>
<div id="keyPressed"> Keys not Pressed</div>
<strong>
<div id="header"><br>Time Idle:</br></div>
<div id="idle"></div>
</strong>

Categories