Idle timeout warning modal working on screen reader - javascript

I need help with a modal that fires when user is idle. It works great until I test on Firefox with NVDA running. There are issues with focus when using the arrow keys and when I swipe on a mobile. When the modal appears and the user uses arrow or swipes the focus will bounce from the yes button to the header after a few seconds if I wait to click it. I have loaded the working example to: https://jsfiddle.net/ncanqaam/
I changed the idle time period to one minute and removed a portion which calls the server to extend the user's session.
var state ="L";
var timeoutPeriod = 540000;
var oneMinute = 60000;
var sevenMinutes = 60000;
var lastActivity = new Date();
function getIdleTime() {
return new Date().getTime() - lastActivity.getTime();
}
//Add Movement Detection
function addMovementListener() {
$(document).on('mousemove', onMovementHandler);
$(document).on('keypress', onMovementHandler);
$(document).on('touchstart touchend', onMovementHandler);
}
//Remove Movement Detection
function removeMovementListener() {
$(document).off('mousemove', onMovementHandler);
$(document).off('keypress', onMovementHandler);
$(document).off('touchstart touchend', onMovementHandler);
}
//Create Movement Handler
function onMovementHandler(ev) {
lastActivity = new Date();
console.log("Something moved, idle time = " + lastActivity.getTime());
}
function hide() {
$('#overlayTY').removeClass('opened'); // remove the overlay in order to make the main screen available again
$('#overlayTY, #modal-session-timeout').css('display', 'none'); // hide the modal window
$('#modal-session-timeout').attr('aria-hidden', 'true'); // mark the modal window as hidden
$('#modal-session-timeout').removeAttr('aria-hidden'); // mark the main page as visible
}
if (state == "L") {
$(document).ready(function() {
//Call Event Listerner to for movement detection
addMovementListener();
setInterval(checkIdleTime, 5000);
});
function endSession() {
console.log('Goodbye!');
}
var modalActive = false;
function checkIdleTime() {
var idleTime = getIdleTime();
console.log("The total idle time is " + idleTime / oneMinute + " minutes.");
if (idleTime > sevenMinutes) {
var prevFocus = $(document.activeElement);
console.log('previously: ' + prevFocus);
var modal = new window.AccessibleModal({
mainPage: $('#oc-container'),
overlay: $('#overlayTY').css('display', 'block'),
modal: $('#modal-session-timeout')
});
if (modalActive === false) {
console.log(modalActive);
$('#modal-session-timeout').insertBefore('#oc-container');
$('#overlayTY').insertBefore('#modal-session-timeout');
modal.show();
$('#modal-overlay').removeClass('opened');
modalActive = true;
console.log(modalActive);
console.log('the modal is active');
$('.js-timeout-refresh').on('click touchstart touchend', function(){
hide();
modalActive = false;
prevFocus.focus();
addMovementListener();
lastActivity = new Date();
});
$('.js-timeout-session-end').on('click touchstart touchend', function(){
hide();
$('#overlayTY').css('display', 'none');
endSession();
});
}
}
if ($('#overlayTY').css('display') === 'block'){
removeMovementListener();
}
if (idleTime > timeoutPeriod) {
endSession();
}
}
}

Possibles solutions
Disable pointer-events on body when overlay is visible. this will restrict keyboard/swipe events on body elements
Use JS/jQuery to trigger focus on the yes button

The issue is with Voiceover Safari when a user swipes on an anchor or button the focus is set on these elements; however, if the element is an H2 it will not receive focus because natively it is not supposed to receive any. To compensate I attempted to set gesture events on the H2 but, Voiceover Safari needs time to read the element text or label out load, so it prevents any event from firing and this creates a problem when trying to set focus on a modal which loads from a timeout function rather than a clickable element. Hopefully Apple will address this in the future.

Related

Mosueup Hold and Press event

I am trying find a way to detect if button was pressed/hold using mouse up event in jQuery
$("element").mouseup(function(event){
callMe();
});
function callMe(){
alert("called");
}
Any help will be great.
I believe you can detect a long press by using a combination of mousedown and mouseup events. It basically calculates the time the user holds the button for.
Here's a sample code you can try.
var longpress = 2000; // duration you consider a long press
var startTime;
$("#button").on('mousedown', function(e) {
startTime = new Date().getTime();
});
$("#button").on('mouseleave', function(e) {
startTime = 0;
});
$("#button").on('mouseup', function(e) {
if (new Date().getTime() >= (startTime + longpress)) {
alert('long press!');
} else {
alert('short press!');
}
});

How to Monitor user idle in an applet inside a html using java script [duplicate]

Is it possible to detect "idle" time in JavaScript?
My primary use case probably would be to pre-fetch or preload content.
I define idle time as a period of user inactivity or without any CPU usage
Here is a simple script using jQuery that handles mousemove and keypress events.
If the time expires, the page reloads.
<script type="text/javascript">
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
window.location.reload();
}
}
</script>
With vanilla JavaScript:
var inactivityTime = function () {
var time;
window.onload = resetTimer;
// DOM Events
document.onmousemove = resetTimer;
document.onkeydown = resetTimer;
function logout() {
alert("You are now logged out.")
//location.href = 'logout.html'
}
function resetTimer() {
clearTimeout(time);
time = setTimeout(logout, 3000)
// 1000 milliseconds = 1 second
}
};
And initialise the function where you need it (for example: onPageLoad).
window.onload = function() {
inactivityTime();
}
You can add more DOM events if you need to. Most used are:
document.onload = resetTimer;
document.onmousemove = resetTimer;
document.onmousedown = resetTimer; // touchscreen presses
document.ontouchstart = resetTimer;
document.onclick = resetTimer; // touchpad clicks
document.onkeydown = resetTimer; // onkeypress is deprectaed
document.addEventListener('scroll', resetTimer, true); // improved; see comments
Or register desired events using an array
window.addEventListener('load', resetTimer, true);
var events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];
events.forEach(function(name) {
document.addEventListener(name, resetTimer, true);
});
DOM Events list: http://www.w3schools.com/jsref/dom_obj_event.asp
Remember to use window, or document according your needs. Here you can see the differences between them: What is the difference between window, screen, and document in JavaScript?
Code Updated with #frank-conijn and #daxchen improve: window.onscroll will not fire if scrolling is inside a scrollable element, because scroll events don't bubble. In window.addEventListener('scroll', resetTimer, true), the third argument tells the listener to catch the event during the capture phase instead of the bubble phase.
Improving on Equiman's (original) answer:
function idleLogout() {
var t;
window.onload = resetTimer;
window.onmousemove = resetTimer;
window.onmousedown = resetTimer; // catches touchscreen presses as well
window.ontouchstart = resetTimer; // catches touchscreen swipes as well
window.ontouchmove = resetTimer; // required by some devices
window.onclick = resetTimer; // catches touchpad clicks as well
window.onkeydown = resetTimer;
window.addEventListener('scroll', resetTimer, true); // improved; see comments
function yourFunction() {
// your function for too long inactivity goes here
// e.g. window.location.href = 'logout.php';
}
function resetTimer() {
clearTimeout(t);
t = setTimeout(yourFunction, 10000); // time is in milliseconds
}
}
idleLogout();
Apart from the improvements regarding activity detection, and the change from document to window, this script actually calls the function, rather than letting it sit idle by.
It doesn't catch zero CPU usage directly, but that is impossible, because executing a function causes CPU usage. And user inactivity eventually leads to zero CPU usage, so indirectly it does catch zero CPU usage.
I have created a small library that does this:
https://github.com/shawnmclean/Idle.js
Description:
Tiny JavaScript library to report activity of user in the browser
(away, idle, not looking at webpage, in a different tab, etc). that is independent of any
other JavaScript libraries such as jQuery.
Visual Studio users can get it from NuGet by:
Install-Package Idle.js
Here is a rough jQuery implementation of tvanfosson's idea:
$(document).ready(function(){
idleTime = 0;
//Increment the idle time counter every second.
var idleInterval = setInterval(timerIncrement, 1000);
function timerIncrement()
{
idleTime++;
if (idleTime > 2)
{
doPreload();
}
}
//Zero the idle timer on mouse movement.
$(this).mousemove(function(e){
idleTime = 0;
});
function doPreload()
{
//Preload images, etc.
}
})
Similar to Peter J's solution (with a jQuery custom event)...
// Use the jquery-idle-detect.js script below
$(window).on('idle:start', function() {
// Start your prefetch, etc. here...
});
$(window).on('idle:stop', function() {
// Stop your prefetch, etc. here...
});
File jquery-idle-detect.js
(function($, $w) {
// Expose configuration option
// Idle is triggered when no events for 2 seconds
$.idleTimeout = 2000;
// Currently in idle state
var idle = false;
// Handle to idle timer for detection
var idleTimer = null;
// Start the idle timer and bind events on load (not DOM-ready)
$w.on('load', function() {
startIdleTimer();
$w.on('focus resize mousemove keyup', startIdleTimer)
.on('blur', idleStart) // Force idle when in a different tab/window
;
]);
function startIdleTimer() {
clearTimeout(idleTimer); // Clear prior timer
if (idle) $w.trigger('idle:stop'); // If idle, send stop event
idle = false; // Not idle
var timeout = ~~$.idleTimeout; // Option to integer
if (timeout <= 100)
timeout = 100; // Minimum 100 ms
if (timeout > 300000)
timeout = 300000; // Maximum 5 minutes
idleTimer = setTimeout(idleStart, timeout); // New timer
}
function idleStart() {
if (!idle)
$w.trigger('idle:start');
idle = true;
}
}(window.jQuery, window.jQuery(window)))
You can do it more elegantly with Underscore.js and jQuery:
$('body').on("click mousemove keyup", _.debounce(function(){
// do preload here
}, 1200000)) // 20 minutes debounce
My answer was inspired by vijay's answer, but is a shorter, more general solution that I thought I'd share for anyone it might help.
(function () {
var minutes = true; // change to false if you'd rather use seconds
var interval = minutes ? 60000 : 1000;
var IDLE_TIMEOUT = 3; // 3 minutes in this example
var idleCounter = 0;
document.onmousemove = document.onkeypress = function () {
idleCounter = 0;
};
window.setInterval(function () {
if (++idleCounter >= IDLE_TIMEOUT) {
window.location.reload(); // or whatever you want to do
}
}, interval);
}());
As it currently stands, this code will execute immediately and reload your current page after 3 minutes of no mouse movement or key presses.
This utilizes plain vanilla JavaScript and an immediately-invoked function expression to handle idle timeouts in a clean and self-contained manner.
All the previous answers have an always-active mousemove handler. If the handler is jQuery, the additional processing jQuery performs can add up. Especially if the user is using a gaming mouse, as many as 500 events per second can occur.
This solution avoids handling every mousemove event. This result in a small timing error, but which you can adjust to your need.
function setIdleTimeout(millis, onIdle, onUnidle) {
var timeout = 0;
startTimer();
function startTimer() {
timeout = setTimeout(onExpires, millis);
document.addEventListener("mousemove", onActivity);
document.addEventListener("keydown", onActivity);
document.addEventListener("touchstart", onActivity);
}
function onExpires() {
timeout = 0;
onIdle();
}
function onActivity() {
if (timeout) clearTimeout(timeout);
else onUnidle();
//since the mouse is moving, we turn off our event hooks for 1 second
document.removeEventListener("mousemove", onActivity);
document.removeEventListener("keydown", onActivity);
document.removeEventListener("touchstart", onActivity);
setTimeout(startTimer, 1000);
}
}
http://jsfiddle.net/9exz43v2/
I had the same issue and I found a quite good solution.
I used jquery.idle and I only needed to do:
$(document).idle({
onIdle: function(){
alert('You did nothing for 5 seconds');
},
idle: 5000
})
See JsFiddle demo.
(Just for information: see this for back-end event tracking Leads browserload)
If you are targeting a supported browser (Chrome or Firefox as of December 2018) you can experiment with the requestIdleCallback and include the requestIdleCallback shim for unsupported browsers.
You could probably hack something together by detecting mouse movement on the body of the form and updating a global variable with the last movement time. You'd then need to have an interval timer running that periodically checks the last movement time and does something if it has been sufficiently long since the last mouse movement was detected.
I wrote a small ES6 class to detect activity and otherwise fire events on idle timeout. It covers keyboard, mouse and touch, can be activated and deactivated and has a very lean API:
const timer = new IdleTimer(() => alert('idle for 1 minute'), 1000 * 60 * 1);
timer.activate();
It does not depend on jQuery, though you might need to run it through Babel to support older browsers.
https://gist.github.com/4547ef5718fd2d31e5cdcafef0208096
(Partially inspired by the good core logic of Equiman's answer.)
sessionExpiration.js
sessionExpiration.js is lightweight yet effective and customizable. Once implemented, use in just one row:
sessionExpiration(idleMinutes, warningMinutes, logoutUrl);
Affects all tabs of the browser, not just one.
Written in pure JavaScript, with no dependencies. Fully client side.
(If so wanted.) Has warning banner and countdown clock, that is cancelled by user interaction.
Simply include the sessionExpiration.js, and call the function, with arguments [1] number of idle minutes (across all tabs) until user is logged out, [2] number of idle minutes until warning and countdown is displayed, and [3] logout url.
Put the CSS in your stylesheet. Customize it if you like. (Or skip and delete banner if you don't want it.)
If you do want the warning banner however, then you must put an empty div with ID sessExpirDiv on your page (a suggestion is putting it in the footer).
Now the user will be logged out automatically if all tabs have been inactive for the given duration.
Optional: You may provide a fourth argument (URL serverRefresh) to the function, so that a server side session timer is also refreshed when you interact with the page.
This is an example of what it looks like in action, if you don't change the CSS.
Try this code. It works perfectly.
var IDLE_TIMEOUT = 10; //seconds
var _idleSecondsCounter = 0;
document.onclick = function () {
_idleSecondsCounter = 0;
};
document.onmousemove = function () {
_idleSecondsCounter = 0;
};
document.onkeypress = function () {
_idleSecondsCounter = 0;
};
window.setInterval(CheckIdleTime, 1000);
function CheckIdleTime() {
_idleSecondsCounter++;
var oPanel = document.getElementById("SecondsUntilExpire");
if (oPanel)
oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + "";
if (_idleSecondsCounter >= IDLE_TIMEOUT) {
alert("Time expired!");
document.location.href = "SessionExpired.aspx";
}
}
<script type="text/javascript">
var idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
idleInterval = setInterval(timerIncrement, 60000); // 1 minute
//Zero the idle timer on mouse movement.
$('body').mousemove(function (e) {
//alert("mouse moved" + idleTime);
idleTime = 0;
});
$('body').keypress(function (e) {
//alert("keypressed" + idleTime);
idleTime = 0;
});
$('body').click(function() {
//alert("mouse moved" + idleTime);
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 10) { // 10 minutes
window.location.assign("http://www.google.com");
}
}
</script>
I think this jQuery code is perfect one, though copied and modified from above answers!!
Do not forgot to include the jQuery library in your file!
Pure JavaScript with a properly set reset time and bindings via addEventListener:
(function() {
var t,
timeout = 5000;
function resetTimer() {
console.log("reset: " + new Date().toLocaleString());
if (t) {
window.clearTimeout(t);
}
t = window.setTimeout(logout, timeout);
}
function logout() {
console.log("done: " + new Date().toLocaleString());
}
resetTimer();
//And bind the events to call `resetTimer()`
["click", "mousemove", "keypress"].forEach(function(name) {
console.log(name);
document.addEventListener(name, resetTimer);
});
}());
The problem with all these solutions, although correct, is they are impractical, when taking into account the session timeout valuable set, using PHP, .NET or in the Application.cfc file for ColdFusion developers.
The time set by the above solution needs to sync with the server-side session timeout. If the two do not sync, you can run into problems that will just frustrate and confuse your users.
For example, the server side session timeout might be set to 60 minutes, but the user may believe that he/she is safe, because the JavaScript idle time capture has increased the total amount of time a user can spend on a single page. The user may have spent time filling in a long form, and then goes to submit it. The session timeout might kick in before the form submission is processed.
I tend to just give my users 180 minutes, and then use JavaScript to automatically log the user out. Essentially, using some of the code above, to create a simple timer, but without the capturing mouse event part.
In this way my client side and server-side time syncs perfectly. There is no confusion, if you show the time to the user in your UI, as it reduces. Each time a new page is accessed in the CMS, the server side session and JavaScript timer are reset. Simple and elegant. If a user stays on a single page for more than 180 minutes, I figure there is something wrong with the page, in the first place.
You can use the below mentioned solution
var idleTime;
$(document).ready(function () {
reloadPage();
$('html').bind('mousemove click mouseup mousedown keydown keypress keyup submit change mouseenter scroll resize dblclick', function () {
clearTimeout(idleTime);
reloadPage();
});
});
function reloadPage() {
clearTimeout(idleTime);
idleTime = setTimeout(function () {
location.reload();
}, 3000);
}
I wrote a simple jQuery plugin that will do what you are looking for.
https://github.com/afklondon/jquery.inactivity
$(document).inactivity( {
interval: 1000, // the timeout until the inactivity event fire [default: 3000]
mouse: true, // listen for mouse inactivity [default: true]
keyboard: false, // listen for keyboard inactivity [default: true]
touch: false, // listen for touch inactivity [default: true]
customEvents: "customEventName", // listen for custom events [default: ""]
triggerAll: true, // if set to false only the first "activity" event will be fired [default: false]
});
The script will listen for mouse, keyboard, touch and other custom events inactivity (idle) and fire global "activity" and "inactivity" events.
I have tested this code working file:
var timeout = null;
var timee = '4000'; // default time for session time out.
$(document).bind('click keyup mousemove', function(event) {
if (timeout !== null) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
timeout = null;
console.log('Document Idle since '+timee+' ms');
alert("idle window");
}, timee);
});
Is it possible to have a function run every 10 seconds, and have that check a "counter" variable? If that's possible, you can have an on mouseover for the page, can you not?
If so, use the mouseover event to reset the "counter" variable. If your function is called, and the counter is above the range that you pre-determine, then do your action.
Here is the best solution I have found:
Fire Event When User is Idle
Here is the JavaScript:
idleTimer = null;
idleState = false;
idleWait = 2000;
(function ($) {
$(document).ready(function () {
$('*').bind('mousemove keydown scroll', function () {
clearTimeout(idleTimer);
if (idleState == true) {
// Reactivated event
$("body").append("<p>Welcome Back.</p>");
}
idleState = false;
idleTimer = setTimeout(function () {
// Idle Event
$("body").append("<p>You've been idle for " + idleWait/1000 + " seconds.</p>");
idleState = true; }, idleWait);
});
$("body").trigger("mousemove");
});
}) (jQuery)
I use this approach, since you don't need to constantly reset the time when an event fires. Instead, we just record the time, and this generates the idle start point.
function idle(WAIT_FOR_MINS, cb_isIdle) {
var self = this,
idle,
ms = (WAIT_FOR_MINS || 1) * 60000,
lastDigest = new Date(),
watch;
//document.onmousemove = digest;
document.onkeypress = digest;
document.onclick = digest;
function digest() {
lastDigest = new Date();
}
// 1000 milisec = 1 sec
watch = setInterval(function() {
if (new Date() - lastDigest > ms && cb_isIdel) {
clearInterval(watch);
cb_isIdle();
}
}, 1000*60);
},
Based on the inputs provided by equiman:
class _Scheduler {
timeoutIDs;
constructor() {
this.timeoutIDs = new Map();
}
addCallback = (callback, timeLapseMS, autoRemove) => {
if (!this.timeoutIDs.has(timeLapseMS + callback)) {
let timeoutID = setTimeout(callback, timeLapseMS);
this.timeoutIDs.set(timeLapseMS + callback, timeoutID);
}
if (autoRemove !== false) {
setTimeout(
this.removeIdleTimeCallback, // Remove
10000 + timeLapseMS, // 10 secs after
callback, // the callback
timeLapseMS, // is invoked.
);
}
};
removeCallback = (callback, timeLapseMS) => {
let timeoutID = this.timeoutIDs.get(timeLapseMS + callback);
if (timeoutID) {
clearTimeout(timeoutID);
this.timeoutIDs.delete(timeLapseMS + callback);
}
};
}
class _IdleTimeScheduler extends _Scheduler {
events = [
'load',
'mousedown',
'mousemove',
'keydown',
'keyup',
'input',
'scroll',
'touchstart',
'touchend',
'touchcancel',
'touchmove',
];
callbacks;
constructor() {
super();
this.events.forEach(name => {
document.addEventListener(name, this.resetTimer, true);
});
this.callbacks = new Map();
}
addIdleTimeCallback = (callback, timeLapseMS) => {
this.addCallback(callback, timeLapseMS, false);
let callbacksArr = this.callbacks.get(timeLapseMS);
if (!callbacksArr) {
this.callbacks.set(timeLapseMS, [callback]);
} else {
if (!callbacksArr.includes(callback)) {
callbacksArr.push(callback);
}
}
};
removeIdleTimeCallback = (callback, timeLapseMS) => {
this.removeCallback(callback, timeLapseMS);
let callbacksArr = this.callbacks.get(timeLapseMS);
if (callbacksArr) {
let index = callbacksArr.indexOf(callback);
if (index !== -1) {
callbacksArr.splice(index, 1);
}
}
};
resetTimer = () => {
for (let [timeLapseMS, callbacksArr] of this.callbacks) {
callbacksArr.forEach(callback => {
// Clear the previous IDs
let timeoutID = this.timeoutIDs.get(timeLapseMS + callback);
clearTimeout(timeoutID);
// Create new timeout IDs.
timeoutID = setTimeout(callback, timeLapseMS);
this.timeoutIDs.set(timeLapseMS + callback, timeoutID);
});
}
};
}
export const Scheduler = new _Scheduler();
export const IdleTimeScheduler = new _IdleTimeScheduler();
As simple as it can get, detect when the mouse moves only:
var idle = false;
document.querySelector('body').addEventListener('mousemove', function(e) {
if(idle!=false)
idle = false;
});
var idleI = setInterval(function()
{
if(idle == 'inactive')
{
return;
}
if(idle == true)
{
idleFunction();
idle = 'inactive';
return;
}
idle = true;
}, 30000); // half the expected time. Idle will trigger after 60 s in this case.
function idleFuntion()
{
console.log('user is idle');
}
Here is an AngularJS service for accomplishing in Angular.
/* Tracks now long a user has been idle. secondsIdle can be polled
at any time to know how long user has been idle. */
fuelServices.factory('idleChecker',['$interval', function($interval){
var self = {
secondsIdle: 0,
init: function(){
$(document).mousemove(function (e) {
self.secondsIdle = 0;
});
$(document).keypress(function (e) {
self.secondsIdle = 0;
});
$interval(function(){
self.secondsIdle += 1;
}, 1000)
}
}
return self;
}]);
Keep in mind this idle checker will run for all routes, so it should be initialized in .run() on load of the angular app. Then you can use idleChecker.secondsIdle inside each route.
myApp.run(['idleChecker',function(idleChecker){
idleChecker.init();
}]);
Surely you want to know about window.requestIdleCallback(), which queues a function to be called during a browser's idle periods.
You can see an elegant usage of this API in the Quicklink repo.
const requestIdleCallback = window.requestIdleCallback ||
function (cb) {
const start = Date.now();
return setTimeout(function () {
cb({
didTimeout: false,
timeRemaining: function () {
return Math.max(0, 50 - (Date.now() - start));
},
});
}, 1);
};
The meaning of the code above is: if the browser supports requestIdleCallback (check the compatibility), uses it. If is not supported, uses a setTimeout(()=> {}, 1) as fallback, which should queue the function to be called at the end of the event loop.
Then you can use it like this:
requestIdleCallback(() => {...}, {
timeout: 2000
});
The second parameter is optional, you might want to set a timeout if you want to make sure the function is executed.
You could probably detect inactivity on your web page using the mousemove tricks listed, but that won't tell you that the user isn't on another page in another window or tab, or that the user is in Word or Photoshop, or WoW and just isn't looking at your page at this time.
Generally, I'd just do the prefetch and rely on the client's multi-tasking. If you really need this functionality, you do something with an ActiveX control in Windows, but it's ugly at best.
Debounce is actually a great idea! Here is a version for jQuery-free projects:
const derivedLogout = createDerivedLogout(30);
derivedLogout(); // It could happen that the user is too idle)
window.addEventListener('click', derivedLogout, false);
window.addEventListener('mousemove', derivedLogout, false);
window.addEventListener('keyup', derivedLogout, false);
function createDerivedLogout (sessionTimeoutInMinutes) {
return _.debounce( () => {
window.location = this.logoutUrl;
}, sessionTimeoutInMinutes * 60 * 1000 )
}

jQuery Scroll Timeout

I'm trying to put a delay on page scroll so if I put some animation, it will not ruin. Here is my code:
var lastScrollY = 0,
delayFlag = true,
delayTime = 1000;
$(window).on('scroll', function(e) {
if(delayFlag == true) {
delayFlag = false;
var posY = $(this).scrollTop(),
sectionH = $('.page').height(),
multiplier = (Math.round(lastScrollY / sectionH));
if(lastScrollY > posY) {
$(window).scrollTop((multiplier - 1) * sectionH);
}
else {
$(window).scrollTop((multiplier + 1) * sectionH);
}
lastScrollY = posY;
setTimeout(function() { delayFlag = true }, delayTime);
}
else {
e.preventDefault();
}
});
jQuery preventDefault() is not working. Is there any way I can put some delay on scroll event?
e.preventDefault(); is for preventing the default action of an event. For example, clicking on an anchor will cause the page to navigate to the address stored on the anchor's href, and calling e.preventDefault(); in an anchor's click event will cause this navigation to not happen.
e.preventDefault(); does not, however, cancel the event that just occurred. Calling it in the onchange event of a form input will not revert its value back to what it just was, and calling it in the scroll event will not cancel the scroll.
While I wouldn't recommend this, from a UX perspective (personally, I hate pages that stop me from going someplace in the site, just so I have to watch their ad or whathaveyou, and I'm fairly sure I'm not the only one...), what you might be able to do, rather than capture the scroll event, is turn off scrolling for the area to start with.
So, have something along these lines (example jsFiddle: http://jsfiddle.net/mori57/cmLun/):
In CSS:
.noscroll {
overflow:hidden;
}
And in your JS:
var lastScrollY = 0,
delayFlag = true,
delayTime = 1000;
$(function(){
$("body").addClass("noscroll");
window.setTimeout(function(){
$("body").removeClass("noscroll");
}, delayTime );
});

Why jQuery doing unwanted multiple actions of single command?

When i resize browser the it gives multiple alerts. I used "return false" not working.
If I used unbind()/unbind('resize') then it works but it creates an other problem- the resize() function stops working from second time browser/window resize.
My code-
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
alert($(".myclass").parent().width());
$(window).bind('resize',function() {
alert($(".myclass").parent().width());
});
});
</script>
<section class="myclass"></section>
This is not an issue with jQuery, but on the browser's implementation of resize.
Depending which browser you use it may trigger intermediate resizes, or a resize when your mouse is released only.
Because the resize triggers everytime the browser changes.
If you are resizing 100 pixels it can trigger up to 100 times.
Something like this should work and trigger only once you stopped resizing the window:
var resizing = false, stopedResizing = true;
$(window).bind('resize',function() {
if(!resizing){
console.log("started resizing. Width = " + $(".myclass").parent().width());
resizing = true;
}
stopedResizing = false;
setTimeout(function(){
if(!stopedResizing){
stopedResizing = true;
setTimeout(function(){
if(stopedResizing && resizing){
resizing = false;
console.log('Stoped resizing. Width = ' + $(".myclass").parent().width());
}
}, 500);
}
}, 500);
});
You could do something like:
$(document).ready(function(e) {
alert($(".myclass").parent().width());
var lastTime = 0;
$(window).bind('resize',function() {
var currentTime = new Date().time();
if(currentTime > lastTime + 5000)
alert($(".myclass").parent().width());
lastTime = currentTime;
});
});
...so that it will only fire on resizes at least 5 seconds apart. Normally though, you'd want to act when resizing stops, not when it starts.
This code fires ones on mouseover of the window after the a resize event as occurred.
$(document).ready(function() {
var windowResized = false;
function callFunction() {
console.log("I am called once after window resize");
}
$(window).mouseover(function() {
if (windowResized == true) {
callFunction();
windowResized = false;
}
})
$(window).resize(function() {
windowResized = true;
});
})

Changing HTML on click in D3.js disables doubleclick [duplicate]

I've toggled click event to a node and I want to toggle a dbclick event to it as well. However it only triggers the click event when I dbclick on it.
So How do I set both events at the same time?
You have to do your "own" doubleclick detection
Something like that could work:
var clickedOnce = false;
var timer;
$("#test").bind("click", function(){
if (clickedOnce) {
run_on_double_click();
} else {
timer = setTimeout(function() {
run_on_simple_click(parameter);
}, 150);
clickedOnce = true;
}
});
function run_on_simple_click(parameter) {
alert(parameter);
alert("simpleclick");
clickedOnce = false;
}
function run_on_double_click() {
clickedOnce = false;
clearTimeout(timer);
alert("doubleclick");
}
Here is a working JSFiddle
For more information about what delay you should use for your timer, have a look here : How to use both onclick and ondblclick on an element?
$("#test-id").bind("click dblclick", function(){alert("hello")});
Works for both click and dblclick
EDIT --
I think its not possible. I was trying something like this.
$("#test").bind({
dblclick: function(){alert("Hii")},
mousedown: function(){alert("hello")}
});
But its not possible to reach double click without going through single click. I tried mouse down but it does not give any solution.
I pretty much used the same logic as Jeremy D.
However, in my case, it was more neat to solve this thing with anonymous functions, and a little slower double click timeout:
dblclick_timer = false
.on("click", function(d) {
// if double click timer is active, this click is the double click
if ( dblclick_timer )
{
clearTimeout(dblclick_timer)
dblclick_timer = false
// double click code code comes here
console.log("double click fired")
}
// otherwise, what to do after single click (double click has timed out)
else dblclick_timer = setTimeout( function(){
dblclick_timer = false
// single click code code comes here
console.log("single click fired")
}, 250)
})
you need to track double click and if its not a double click perform click action.
Try this
<p id="demo"></p>
<button id='btn'>Click and DoubleClick</button>
<script>
var doubleclick =false;
var clicktimeoutid = 0;
var dblclicktimeoutid = 0;
var clickcheck = function(e){
if(!clicktimeoutid)
clicktimeoutid = setTimeout(function(){
if(!doubleclick)
performclick(e);
clicktimeoutid =0;
},300);
}
var performclick =function(e){
document.getElementById("demo").innerHTML += 'click';
}
var performdblclick = function(e)
{
doubleclick = true;
document.getElementById("demo").innerHTML += 'dblclick';
dblclicktimeoutid = setTimeout(function(){doubleclick = false},800);
};
document.getElementById("btn").ondblclick = performdblclick;
document.getElementById("btn").onclick=clickcheck;
</script>
a slightly different approach - The actual click comparison happens later in the timeOut function, after a preset interval... till then we simply keep tab on the flags.
& with some simple modifications (click-counter instead of flags) it can also be extended to any number of rapid successive clicks (triple click, et al), limited by practicality.
var clicked = false,
dblClicked = false,
clickTimer;
function onClick(param){
console.log('Node clicked. param - ',param);
};
function onDoubleClick(param){
console.log('Node Double clicked. param - ',param);
};
function clickCheck(param){
if (!clicked){
clicked = true;
clickTimer = setTimeout(function(){
if(dblClicked){
onDoubleClick(param);
}
else if(clicked){
onClick(param);
}
clicked = false;
dblClicked = false;
clearTimeout(clickTimer);
},150);
} else {
dblClicked = true;
}
};

Categories

Resources