Cannot understand why event is undefined - javascript

I'm sorry, I feel this is a really classic issue but since I'm learning I don't know why it's not working in my case.
I'm trying to have a script that detect your idle time and if so, execute a function that get your mouse position.
In order to do that, I have the function TimerIncrement() that can check 2 seconds of inactivity, if so I would like to execute another function called GetMousePos in order to get the mouse position and to have a console.log of it.
I've tried looking online and on the forums but nothing I have been doing is helping.
Thanks for the precious help.
var idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 1000); // 1s
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 2) { // 2sec
getMousePos();
idleTime = 0; // reset timer
}
}
function getMousePos(event) {
x = event.pageX;
y = event.pageY;
console.log(x);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

So you're calling getMousePos which takes a parameter of event and you are not passing anything to it hence the Cannot read property 'pageX' as event.pageX (event not defined). You can only get to the event object ON a event callback so I am assuming you want to get the last event you have seen if any.
The below should work for you, storing the lastEvent seen you should then be able to get the info you want. Hopefully, this code example makes you understand what you were missing.
var idleTime = 0;
var lastEvent = undefined;
$(document).ready(function () {
//Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 1000); // 1s
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
lastEvent = e;
});
$(this).keypress(function (e) {
idleTime = 0;
lastEvent = e;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 2) { // 2sec
getMousePos(lastEvent);
idleTime = 0; // reset timer
}
}
function getMousePos(event) {
if (!event) {
console.log("No mouse or keypress has been executed yet");
return;
}
x = event.pageX;
y = event.pageY;
console.log(x);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

You can't get the mouse position without an event, so we need to track the mousemove and save the latest position.
$(function() {
let idleTime = 0
let pos = []
let timer = window.setInterval(incTime, 1000)
function incTime() {
idleTime++
checkTime()
$('.time span')[0].innerText = idleTime
}
function checkTime() {
if (idleTime > 2) {
resetTime()
$('.x span')[0].innerText = pos[0]
$('.y span')[0].innerText = pos[1]
}
}
$(document).on('mousemove', e => {
window.clearInterval(timer)
resetTime()
pos[0] = e.pageX
pos[1] = e.pageY
timer = window.setInterval(incTime, 1000)
})
function resetTime() {
idleTime = 0
$('.time span')[0].innerText = idleTime
}
})
<div class="time">Idle time: <span>0</span></div>
<div class="x">X: <span></span></div>
<div class="y">Y: <span></span></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

Detect inactivity on touch devices with javascript

I've been researching and found code that detects inactivity(when the user doesn't touch the screen) after the user goes idle for x amount of time which works perfectly when using the mouse but when I try using this with touch screen devices, it doesn't detect my finger or work. I've added a lot of DOM events such as "touchstart", "touchmove", "touchend", "touchcancel" and others but they don't seem to work either. Here is my code
var idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 3000);
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 1) {
alert("ok");
}
}
I will adjust the timer (you sayd you want an update every minute but you set you setInterval to 3000 millisec and i will try with this:
var idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 60000);
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
//Zero the idle timer on touch events.
$(this).bind('touchstart', function(){
idleTime = 0;
});
$(this).bind('touchmove', function(){
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 1) {
alert("ok");
}
}
Try adding this code:
$(this).bind('touchstart touchmove click', function(){
idleTime = 0;
}

How can I track mouse position every 500 milliseconds for 10 seconds?

I want to capture the mouse pointer position after every 500 milliseconds for 10 secs lets suppose. Can someone please help?!
I tried using 'mousemove' event but couldn't move any further with this approach. Here's the code, hope this helps you. The removeEventListner on mousemove is not working correctly.
var loadTime;
var loadDate;
var clickTime;
var mousePositions = [];
var closeCapture = false;
var isTimerON = false;
var timer_div = document.getElementById('timer-section');
var x , y;
function mouseUpdate(e) {
if (isTimerON) {
x = e.pageX;
y = e.pageY;
// if the timer is ON and position capturing is OPEN then push
// the last pointer position to the array
if (!closeCapture){
var mouseUpdate = setInterval(function () {
mousePositions.push({
pos_x : x,
pos_y : y
});
}, 500);
}
}
else{
document.removeEventListener('mousemove', mouseUpdate);
}
}
function setTimer (time) {
var x = time;
document.addEventListener('mousemove', mouseUpdate);
if (isTimerON) {
var timer = setInterval(function() {
if (x >= 0){
timer_div.innerHTML = x;
console.log(x);
x--;
}
else {
//console.log(mousePositions);
isTimerON = false;
closeCapture = true;
clearInterval(timer);
console.log("timer off capture closed");
}
},1000);
}
}
function makeTime(x) {
return x.getHours() + " : " + x.getMinutes() + " : " + x.getSeconds();
}
function tii() {
isTimerON = true;
setTimer(10);
document.removeEventListener('click', tii);
}
document.addEventListener('DOMContentLoaded', function () {
loadCDate = new Date();
loadTime = makeTime(loadCDate);
console.log(loadTime);
document.addEventListener('click', tii);
});
<div id="timer-section"></div>
I would suggest capturing mousemove events for the duration of your time limit (in this example I've set limit to 10 seconds). The throttle variable ensures you only capture once per that many milliseconds (in this example 500ms).
You can use the x/y co-ordinates of the mousemove event to get the current position of the mouse.
const limit = 10000
const throttle = 500
const start = (new Date).getTime()
let last = (new Date).getTime()
const handleMouseMove = (event) => {
const now = (new Date).getTime()
if ((now - start) > limit) {
document.removeEventListener('mousemove', handleMouseMove)
return
}
if ((now - last) < throttle) {
return
}
last = now
// do whatever you want to do within your time limit here
}
document.addEventListener('mousemove', handleMouseMove)
I think you need this http://devdocs.io/lodash~4/index#throttle. the throttle function will make you capture event in a setup freq. If you code is handle every callback of mouse event. you program will be freeze.

How to catch events to clear cookies?

I have developed a login page. I am saving sessionId in local storage on login and I want to clear it after some time. But that to be if someone(logged-user) not active for some time. If he is active, I don't want to clear. But I did that even he is active also, I am clearing the local storage. Please help to know how to catch he is active or not.
localStorage.setItem('userId', data.id);
localStorage.setItem('user', data.phone);
localStorage.setItem('sessionId', (Math.random()*1e64).toString(36));
var interval = setInterval(function(){
console.log('In localStorage');
localStorage.removeItem('sessionId');
clearInterval(interval);
alert('Session expired!!')
}, (30*60*1000));
You can just check use a setInterval:
var idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 60000); // 1 minute
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 19) { // 20 minutes
localStorage.removeItem('sessionId');
}
}
Answer borrowed from here

Using system clock for accurate idle timeout warning

I am working on a modal which will alert users of a pending logout due to idle time. Overall it works, but I notice the timer is not 100% accurate. I know there are issues with setInterval and accuracy. I still seeing discrepancies and will welcome a suggestion on how to improve my code.
var sessionTimeoutPeriod = 240;
var state = "L";
var timeoutPeriod = sessionTimeoutPeriod * 1000;
var logout = Math.floor(timeoutPeriod / 60000);
var idleInterval;
if (state == "L" || state == "O" || state == "C") {
var idleTime = 0;
$(document).ready(function() {
//Zero the idle timer on mouse movement.
$(this).mousemove(function(e) {
idleTime = 0;
console.log("The mouse moved, idle time = " + idleTime);
});
$(this).keypress(function(e) {
idleTime = 0;
console.log("A key was pressed, idle time = " + idleTime);
});
idleInterval = setInterval(timerIncrement, 60000); // 1 minute
});
function timerIncrement() {
idleTime++;
console.log("The total idle time is "+idleTime+ " minutes.");
if (idleTime >= 1) {
console.log("The modal will fire if idle time = " +idleTime);
var modal = new window.AccessibleModal({
mainPage: $('#main'),
overlay: $('#overlay').css('display', 'block'),
modal: $('#modal-session-timeout'),
prevFocus: $('#main')
});
modal.show();
$('#modal-overlay').removeClass('opened');
$('.js-timeout-refresh, .xClose').click(function() {
modal.hide();
$('#overlayTY').css('display', 'none');
idleTime = 0;
console.log("The total idle time is "+idleTime+ " minutes.");
});
$('.js-timeout-session-end').click(function() {
modal.hide();
$('#overlay').css('display', 'none');
endSession();
});
console.log(idleTime);
}
if (idleTime == logout) { // 9 minutes
endSession();
}
var endSession = function() {
document.location.replace(logoutPageUrl);
};
}
}
Instead of relying on the interval to determine how much time has passed, you could validate how much time has passed manually by comparing the current time against the time since last activity.
This way you can increase the checking interval without having to modify the code. The discrepancy will never be higher then then the interval timeout now, the discrepancy will also not change incrementally, it will always be lower or equal to the interval ( in worst case scenario ).
Here is a basic example.
var sessionTimeoutPeriod = 240;
var timeoutPeriod = sessionTimeoutPeriod * 1000;
var oneMinute = 60000;
var showIdlePopUpTimeOut = oneMinute * 2;
var lastActivity = new Date();
function getIdleTime() {
return new Date().getTime() - lastActivity.getTime();
}
$(document).ready(function () {
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
console.log("The mouse moved, idle time = " + getIdleTime());
lastActivity = new Date();
});
$(this).keypress(function (e) {
console.log("A key was pressed, idle time = " + getIdleTime());
lastActivity = new Date();
});
setInterval(checkIdleTime, 5000);
});
function endSession() {
document.location.replace(logoutPageUrl);
};
function checkIdleTime() {
var idleTime = getIdleTime();
console.log("The total idle time is " + idleTime / oneMinute + " minutes.");
if (idleTime > showIdlePopUpTimeOut) {
var modal = new window.AccessibleModal({
mainPage: $('#main'),
overlay: $('#overlay').css('display', 'block'),
modal: $('#modal-session-timeout'),
prevFocus: $('#main')
});
modal.show();
$('#modal-overlay').removeClass('opened');
$('.js-timeout-refresh, .xClose').click(function () {
modal.hide();
$('#overlayTY').css('display', 'none');
lastActivity = new Date();
});
$('.js-timeout-session-end').click(function () {
modal.hide();
$('#overlay').css('display', 'none');
endSession();
});
console.log(lastActivity);
}
if (idleTime > timeoutPeriod) { // 4 minutes
endSession();
}
}
The problem is that your function "timerIncrement" checks the difference every minute after loading the page, so you will never get exact 1 minute after last activity.Changing interval from 60000 to 1000 will solve the issue.
You don't even need to calculate diff, you can just reset timeout every time there is activity. like this:
$(this).on("mousemove keypress", function(e) {
clearInterval(idleInterval);
idleInterval = setTimeout(functionThatExecutesAfter1minInactivity, 60000);
});

JQuery - Recording time on mouse hover and on mouse rest?

I would like to record times for two different JavaScript events. One for when the mouse isn't moving, and the other for when the mouse is moving.
$(document).ready(function() {
var timeStart = new Date().getTime();
var elapsedTime = (timeEnd - timeStart)/1000
});
I know of the JQuery event mousemove but am not sure how you would track time when a mouse is moving
Try this:
$(document).ready(function () {
var timer = null;
var idleTime = 0;
timer = setInterval(timerIncrement, 1000);
$(document).bind("mousemove", function (e) {
idleTime = 0;
});
function timerIncrement() {
idleTime = idleTime + 1;
}
});

Categories

Resources