Timeout time counting does not detect input field - javascript

I write method to reset timeout on mouse click, keyup and keypress, but I just realised that it does not check on input field so when I'm actively typing in a field it will timeout.
Here is my code:
var idleInterval = setInterval(timerIncrement, 10000);
var idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
$(this).keyup(function (e) {
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 4) {
window.location.replace('/timeout.aspx');
}
}

You should have all the code inside the document.ready() function.
$(document).ready(function() {
var idleInterval = setInterval(timerIncrement, 10000);
var idleTime = 0;
$(document).on('keyup', function() {
console.log('Keyup Detected');
idleTime = 0;
});
function timerIncrement() {
idleTime++;
if (idleTime > 4)
window.location.replace('/timeout.aspx');
}
});

You can use this jQuery function to detect all key presses on the page:
$(document).on("keypress", function (e) {
idleTime = 0;
});
So your code should look like:
var idleInterval = setInterval(timerIncrement, 10000);
var idleTime = 0;
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 4) {
window.location.replace('/timeout.aspx');
}
}
$(document).ready(function () {
$(this).mousemove(function (e) {
idleTime = 0;
});
$(document).on("keypress", function (e) {
idleTime = 0;
});
});

Related

pos lock on / off page refresh issue time reset

I am working on POS. And I need to achieve lock on/off.
Issue
When lock is on for any number of seconds then During timing counter if user refresh page
then timing counter get reset.
No matter how many time a user refresh the page time get update/reset.
Please suggest any possible solution regarding page refresh.Thanks
My complete code is below
$(document).ready(function () {
//-------------------- pos inactivity code section ----------------------------------
// Get local storage.
local_pos_storage = window.localStorage;
// by default lock is 'on' so set lock key to on.
if (local_pos_storage.getItem("lock") === null) { // if lock is not set.
local_pos_storage.setItem('lock', 'off'); // default turn off lock.
} else if (local_pos_storage.getItem("lock") === "on") {
// alert("lock is on ");
// pos pin show model.
// $("#pos_pin_modal").modal({backdrop: 'static', keyboard: false, show: true});
}
// set button text based.
if (local_pos_storage.getItem('lock') == "on") { // if lock is on.
$('#lock_text').html("Lock On");
} else if (local_pos_storage.getItem('lock') == "off") { // if lock is off.
$('#lock_text').html("Lock Off");
}
var idleInterval;
// anonymous function to check inactivities.
let inactive = function () { // Increment the idle time counter every minute.
clearInterval(idleInterval);
idleInterval = setInterval(function () {
if (local_pos_storage.getItem('lock') == "on") {
console.log(idleTime);
idleTime = idleTime + 1;
if (idleTime > pos_inactive_time) {
// clear interval when pop-up.
clearInterval(idleInterval);
idleTime = 0;
// hide error and success messages before model opens.
$(".pos-pin-error").hide();
$(".pos-pin-success").hide();
$("#pos-pin").val('');
// pos pin show model.
$("#pos_pin_modal").modal({backdrop: 'static', keyboard: false, show: true});
}
}
}, 1000);
// Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
};
//-------------------- pos pin verification ----------------------------------
var idleTime = 0; // set default idle time.
var pos_inactive_time = parseInt('{{ get_pos_inactive_time() }}'); // get pos inactive time.
$(document).ready(function () {
// default inactive method call.
// inactive();
// pos pin model 'access' button clicked
// $(document).on("click","#verify-pos-pin-btn",function(event) {
// $(document).on("keyup change click", "#pos-pin", function (event) {
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 2000; //time in ms, 5 seconds for example
var $input = $('#pos-pin');
//on keyup, start the countdown
$input.on('keyup', function () {
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//on keydown, clear the countdown
$input.on('keydown', function () {
clearTimeout(typingTimer);
});
//user is "finished typing," do something
function doneTyping() {
// $(document).on("keyup change", "#pos-pin", function (event) {
// get pos pin value.
let pos_pin = $('#pos-pin').val()
// pos pin validation.
if (pos_pin == null || pos_pin == "" || pos_pin.length < 4) { // min dights 4
// $(".pos-pin-error").show();
// $(".pos-pin-error").html("Pos Pin is required.");
} else {
// pos pin verification.
$.ajax({
type: "POST",
url: "{{ route('pos.verify.pos.pin') }}",
data: {
'_token': "{{ csrf_token() }}",
'pos_pin': pos_pin
},
cache: false,
success: function (data) {
if (data.success == "2") // error
{
// $(".pos-pin-success").hide();
// $(".pos-pin-error").html(data.message);
// $(".pos-pin-error").show();
} else if (data.success == "1") { // success
if (local_pos_storage.getItem("switch") === "yes") {
pos_pin_turn_on_off();
// alert("switch = yes ");
localStorage.removeItem("switch");
}
$("#pos_pin_modal").modal('hide'); // hide model.
// activate.
inactive();
}
},
error: function (jqXHR, textStatus, errorThrown) {
$(".pos-pin-success").hide();
$(".pos-pin-error").html("Something went wrong!");
$(".pos-pin-error").show();
console.log(JSON.stringify(jqXHR));
console.log("AJAX error aaa: " + textStatus + ' : ' + errorThrown);
}
});
}
}
});
//---------------------------------------------------------- POS-PIN NUMPAD
// only allow 0 to 9 digits only.
$('#pos-pin').keyup(function (e) {
this.value = this.value.replace(/[^0-9\.]/g, '');
});
// pos pin keypad numbers get clicked.
$(".pos-pin-keypad").click(function (event) {
event.preventDefault();
event.stopPropagation();
let value = $(this).attr("data-value");
let old_pos_pin = "";
if (value === "c") { // clear input.
$('#pos-pin').val(""); // clear pos pin input.
} else {
old_pos_pin = $('#pos-pin').val(); // get old pos pin input value.
$('#pos-pin').val(old_pos_pin + value); // append old pos pin input value.
$('#pos-pin').trigger('change');
}
});
//---------------------------------------------------------- POS On/Off press for 2 seconds.
var longpress = 2000;
var start_longpress;
var timer_longpress;
$("#lock_btn").on('mousedown', function (e) {
e.stopPropagation();
e.preventDefault();
start_longpress = new Date().getTime();
timer_longpress = setTimeout(function () {
console.log('long press!');
pos_pin_turn_on_off();
}, longpress);
}).on('mouseleave', function (e) {
start_longpress = 0;
clearTimeout(timer_longpress);
}).on('mouseup', function (e) {
if (new Date().getTime() < (start_longpress + longpress)) {
clearTimeout(timer_longpress);
console.log('breafly press!');
if (local_pos_storage.getItem("switch") === null)
{
local_pos_storage.setItem('switch', 'yes');
}
$('#pos-pin').val(""); // clear pos pin input.
$("#pos_pin_modal").modal({backdrop: 'static', keyboard: false, show: true});
}
});
function pos_pin_turn_on_off() {
// alert("pos_pin_turn_on_off");
// reset idletime when lock button pressed.
idleTime = 0;
let lock = $('#lock_text').text();
if (lock == "Lock On") // turned off functionalotiy.
{
$('#lock_text').text('Lock Off');
local_pos_storage.setItem("lock", 'off');
inactive();
} else { // turn on diable functionality.
$('#lock_text').text('Lock On');
local_pos_storage.setItem('lock', 'on');
inactive();
}
}
}); // document ready

if statement inside of event listener not working for JavaScript

Making this super simple game. You hold the space bar and the timer starts, when you release the space bar it stops and if you have beaten your high score then it will update high score otherwise it resets the timer to 0 and keeps the high score the same. I can't get the high score to stay the same if the timer is under the high number. It changes every time
`use strict`;
let timer = document.getElementById(`number`);
let highScore = document.getElementById(`highNumber`);
let resetBtn = document.getElementById(`resetBtn`);
let timerNumber = 0;
startTimer();
function init() {}
function startTimer() {
document.addEventListener('keydown', (event) => {
if (event.code === 'Space') {
timer.textContent = timerNumber++;
}
});
}
document.addEventListener(`keyup`, (event) => {
if (timer.textContent > highScore.textContent) {
highScore.textContent = timerNumber;
timer.textContent = 0;
timer.textContent = 0;
timerNumber = 0;
}
if (timer.textContent < highScore.textContent) {
timer.textContent = 0;
timer.textContent = 0;
timerNumber = 0;
}
});
function reset() {
resetBtn.addEventListener(`click`, function () {
highScore.innerHTML = 0;
});
}
reset();
Don't add keyup or keydown event to document give it to the <html> tag :
document.querySelector("html").addEventListener('keydown', (event)=>{
//something
});

Stop and run recursion slider JS

I am trying to understand the setTimeout method and recursion.
I have a simple slidshow based on setTimeout recursion. And I want to stop and run it by clicking on two buttons stop and play. I tried many variants, but don't understand how to clear such recursion timeout and then when I click on play, this slider runs from the slide it was stopped.
Recursion slider:
let timer = setTimeout(function slider() {
for (let i = 0; i < images.length; i++) {
images[i].classList.add('hide');
}
currentSlide++;
if (currentSlide > images.length) {
currentSlide = 1;
}
images[currentSlide - 1].classList.remove('hide');
setTimeout(slider, 3000);
}, 0);
Buttons:
stopBtn.addEventListener('click', () => {
clearTimeout(timer);
});
playBtn.addEventListener('click', () => {
setTimeout(timer, 3000);
});
UPD: I've almost achieved the stop/play fuctionality, but when I click on play btn, slideshow continues in 2 slides. And whenever I click on play button the slideshow changes.
timer = setTimeout(function slider() {
for (let i = 0; i < images.length; i++) {
images[i].classList.add('hide');
}
images[currentSlide].classList.remove('hide');
if (currentSlide + 1 === images.length) {
currentSlide = 0;
} else {
currentSlide++;
}
let sllideSwhow = setTimeout(slider, 3000);
stopBtn.addEventListener('click', () => {
clearTimeout(sllideSwhow);
});
playBtn.addEventListener('click', () => {
slider();
});
}, 0);
Finally, I've managed to do it.
function slider() {
for (let i = 0; i < images.length; i++) {
images[i].classList.add('hide');
}
images[currentSlide].classList.remove('hide');
if (currentSlide + 1 === images.length) {
currentSlide = 0;
} else {
currentSlide++;
}
timer = setTimeout(slider, 3000);
}
slider();
stopBtn.addEventListener('click', () => {
clearTimeout(timer);
playing = 0;
});
playBtn.addEventListener('click', () => {
if (!playing) {
playing = 1;
slider();
}
});

Timer Reset Button

Currently I have a timer that counts down from two minutes. What i need is a button that will stop and reset the timer. Here is the code i have.
js
$(function () {
var $startTimer = $('#startTimer');
var $timerDisplay = $('#timerDisplay');
var time = 120;
$timerDisplay.hide();
$startTimer.click(function () {
$startTimer.prop('disabled', true);
$timerDisplay.show();
var timeRemaining = time;
var intervalId = setInterval(function () {
var timeStamp = Math.floor(timeRemaining/60) + ':' + timeRemaining%60;
$timerDisplay.text(timeStamp);
if (timeRemaining === 0) {
clearInterval(intervalId);
$timerDisplay.fadeOut();
alert('Time is up, please submit a vote :)');
$startTimer.prop('disabled', false);
} else {
timeRemaining--;
}
}, 1000);
});
});
HTML
<div id="timerDisplay"></div>
<button id="startTimer">Start Timer</button>
here is a working code pen of the timer but not the color change http://codepen.io/Chevex/pen/RNomGG
Try ...
HTML:
<div id="timerDisplay"></div>
<button id="startTimer">Start Timer</button>
<button id="stopTimer" disabled>Stop and Reset Timer</button>
JS:
$(function () {
var $startTimer = $('#startTimer');
var $stopTimer = $('#stopTimer');
var $timerDisplay = $('#timerDisplay');
var time = 120;
var intervalId;
$timerDisplay.hide();
$startTimer.click(function () {
$startTimer.prop('disabled', true);
$stopTimer.prop('disabled', false);
$timerDisplay.show();
var timeRemaining = time;
intervalId = setInterval(function () {
var timeStamp = Math.floor(timeRemaining / 60) + ':' + timeRemaining % 60;
$timerDisplay.text(timeStamp);
if (timeRemaining === 0) {
clearInterval(intervalId);
$timerDisplay.fadeOut();
alert('Time is up, please submit a vote :)');
$startTimer.prop('disabled', false);
} else {
timeRemaining--;
}
}, 1000);
});
$stopTimer.click(function() {
time = 120;
$startTimer.prop('disabled', false);
$stopTimer.prop('disabled', true);
$timerDisplay.hide();
clearInterval(intervalId);
$timerDisplay.text("");
});
});
Basically, I moved the interval variable and created a stop timer button; the click functionality performs the reset, using the code similar to what you performed before.
jsFiddle: http://jsfiddle.net/rfornal/w29ofkek/
create a input button as follows
<input type='button' value="Stop" onclick="StopTimer();"/>
Change your code to following
var intervalId =null;
$(function () {
var $startTimer = $('#startTimer');
var $timerDisplay = $('#timerDisplay');
var time = 120;
$timerDisplay.hide();
$startTimer.click(function () {
$startTimer.prop('disabled', true);
$timerDisplay.show();
var timeRemaining = time;
intervalId = setInterval(function () {
var timeStamp = Math.floor(timeRemaining/60) + ':' + timeRemaining%60;
$timerDisplay.text(timeStamp);
if (timeRemaining === 0) {
clearInterval(intervalId);
$timerDisplay.fadeOut();
alert('Time is up, please submit a vote :)');
$startTimer.prop('disabled', false);
} else {
timeRemaining--;
}
}, 1000);
});
});
function StopTimer()
{
clearInterval(intervalId);
}

Why isn't .is(":hover") working?

I have this code to fade out some stuff on a page after you don't move your mouse for a second or so:
idleTime = 0;
var idleInterval = setInterval(function() {
idleTime++;
if (idleTime > 1) {
var isHovered = $('.fade-outs').is(":hover");
if(isHovered == false) {
$('.fade-outs').stop().fadeOut();
}
}
}, 1000);
$(document).bind('mousemove mousedown', function(e) {
idleTime = 0;
$('.fade-outs').fadeIn();
});
But, I am getting the following error with $('.fade-outs').is(":hover"); part:
Error: Syntax error, unrecognized expression: hover [http://localhost:5545/assets/js/jquery.min.js:3]
Does anyone know why I am getting this error?
I would try something like this instead:
var idleTimer;
function startTimer() {
stopTimer();
idleTimer = setInterval(function() {
$('.fade-outs').stop().fadeOut();
}, 1000);
}
function stopTimer() {
idleTimer && clearInterval(idleTimer);
}
$(document).on('mousemove', startTimer);
$('.fade-outs').on({
mouseleave: startTimer,
mouseenter: stopTimer,
mousemove: function(e) {
e.stopPropagation();
}
});​
Demo: http://jsfiddle.net/Blender/urzug/4/
Try changing it to this:
idleTime = 0;
var idleInterval = setInterval(function() {
idleTime++;
if (idleTime > 1) {
var isHovered = $('.fade-outs').is(".hover");
if(isHovered == false) {
$('.fade-outs').stop().fadeOut();
}
}
}, 1000);
$(document).bind('mousemove mousedown', function(e){
idleTime = 0;
$('.fade-outs').fadeIn();
});
$('.fade-outs').hover(funciton() { $(this).toggleClass('hover') });

Categories

Resources