Code Monkey home page Code Monkey logo

jquery-idletimer's People

Contributors

altreus avatar charandas avatar evandroflores avatar lboynton avatar mikesherov avatar mociepka avatar paulirish avatar pazepaze avatar stevedavis-tr avatar terminal-case avatar thorst avatar zawaideh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-idletimer's Issues

Demo fiddle not working in IE 11

I don't believe your fiddle is working in IE 11 -- http://jsfiddle.net/thorst/2aGL4/
It loads as 'active' and never changes.

I'm using IE Browser Version 11.850.15063.0
In my implementation with IE 11 and jquery 3.3.1 on Windows 10, the mouse wheel does not work and users can't input into textareas or use dropdown select when idleTimer is instantiated on $(document)

Tag not up-to-date

I saw that the syncTimerId feature is not available through Bower or Grunt, and it's because no tag for 1.1.0 has been released. Any plans of doing that soon, since that feature seems useful for mobile devices?

Not all touch events are handled

We are using this plugin in our project.

Currently we ran into issue that large part of users are coming from mobile devices.

Hence feature-request: Add support for touch events.

JSFiddle sample not working in Chrome with strict MIME type checking

Looks like Chrome with strict MIME type checking enabled will not execute the jsfiddle external JS (http://jsfiddle.net/thorst/2aGL4/4/):

One workaround is to change the external JS from the raw.github link to http://thorst.github.io/jquery-idletimer/prod/src/idle-timer.js

Keep alive method

Would be great if there is any way to call a method with a separated time interval to call to an specific service to mantain the backend session alive

Like:

$( document ).idleTimer( {
	keepAlive:{
		timeout: 5000, //every 5 seconds call a determined backend function
		script: 'http://localhost/wakeup.php'
	}
});

jQuery throwing errors on every event we use for active.

I keep getting:

Uncaught TypeError: ((jQuery.event.special[handleObj.origType] || {}).handle || handleObj.handler).apply is not a function....

for each of the events I use in "events" option.

However, if I change the idleTimer code (line 300) from:

    jqElem.on($.trim((opts.events + " ").split(" ").join("._idleTimer ")), function (e) {
        handleEvent(e);
    }, supportsPassive ? { passive: true } : false);

to:

    jqElem.on($.trim((opts.events + " ").split(" ").join("._idleTimer ")), function (e) {
        handleEvent(e);
    });

It's not happening any more. Seems that the check for support of passive events in combination with jQuery namespaced events doesn't work.

Use it in angular/typescript

I am wondering how to use it in angular project through npm install & import in component?

Npm install jquery-idletimer gives below error

Does not work for iframe?

iframe test

Even if i move and click the mouse in the iframe, it still remains idle. Is there a way around this?

Iframe does not work with document either.

Thanks

Dismissing the timeout dialog between tabs/windows

I've been implementing your plugin today and I think I've run across an issue that is either a bug or an inherent browser problem, but I can't figure out which.

I used one of your examples as my reference implementation, stripping out the keepalive bits because my server side session management has its own timeout mechanism. Your cross-tab/window feature works perfectly for avoiding the popup, but when I dismiss it in one tab, it stays open in the other(s), and they eventually trigger the logout event.

This is my full code, which like I said is mostly the same as your example:

<script>
	(function ($) {
		var
			session = {
				//Logout Settings
				inactiveTimeout: 10000,     //(ms) The time until we display a warning message
				warningTimeout: 30000,      //(ms) The time until we log them out
				minWarning: 5000,           //(ms) If they come back to page (on mobile), The minumum amount, before we just log them out
				warningStart: null,         //Date time the warning was started
				warningTimer: null,         //Timer running every second to countdown to logout
				logout: function () {       //Logout function once warningTimeout has expired
					window.location = '/index.cfm?action=login.logout';
				}
			};

		$(document).on("idle.idleTimer", function (event, elem, obj) {
			//Get time when user was last active
			var
				diff = (+new Date()) - obj.lastActive - obj.timeout,
				warning = (+new Date()) - diff
			;
			
			//On mobile js is paused, so see if this was triggered while we were sleeping
			if (diff >= session.warningTimeout || warning <= session.minWarning) {
				window.location = '/index.cfm?action=login.logout';
			} else {
				//Show dialog, and note the time
				$('#sessionSecondsRemaining').html(Math.round((session.warningTimeout - diff) / 1000));
				$("#sessionTimoutModal").modal("show");
				session.warningStart = (+new Date()) - diff;

				//Update counter downer every second
				session.warningTimer = setInterval(function () {
					var remaining = Math.round((session.warningTimeout / 1000) - (((+new Date()) - session.warningStart) / 1000));
					if (remaining >= 0) {
						$('#sessionSecondsRemaining').html(remaining);
					} else {
						session.logout();
					}
				}, 1000)
			}
		});

		//User clicked ok to extend session
		$("#extendSession").click(function () {
			clearTimeout(session.warningTimer);
		});
		//User clicked logout
		$("#logoutSession").click(function () {
			session.logout();
		});
		
		//Set up the timer, if inactive for 10 seconds log them out
		$(document).idleTimer({
			timeout:session.inactiveTimeout,
			timerSyncId:"compendium-logout-timer"
		});
	})(jQuery);
</script>

Uncaught TypeError: undefined is not a function (on master branch)

Hi there,

I feel this might be my mistake, but if I download the latest version (from dist/, either the minified or unminified version) and include it on my website, with chrome 24.0.1312.56 m I get (also fails on IE)

Uncaught TypeError: undefined is not a function 

Which is weird because I definitively included Jquery before including the file for timer. The error is on this line:

( function( $ ) { # Uncaught TypeError: undefined is not a function 

This diff solves it on my case:

4,5d3
< ( function( $ ) {
< 
143,144d140
< 
< })( jQuery );

$ is jQuery in my application, I guess it would break in some other cases. Frankly, I don't see anything wrong with the code (and I don't know what's causing it!), but this certainly fixes it.

Not triggering idle or active after page load

Please reveiw the code below:

/*! Idle Timer v1.1.0 2016-03-21 | https://github.com/thorst/jquery-idletimer | (c) 2016 Paul Irish | Licensed MIT */
!function(a){a.idleTimer=function(b,c){var d;"object"==typeof b?(d=b,b=null):"number"==typeof b&&(d={timeout:b},b=null),c=c||document,d=a.extend({idle:!1,timeout:3e4,events:"mousemove keydown wheel DOMMouseScroll mousewheel mousedown touchstart touchmove MSPointerDown MSPointerMove"},d);var e=a(c),f=e.data("idleTimerObj")||{},g=function(b){var d=a.data(c,"idleTimerObj")||{};d.idle=!d.idle,d.olddate=+new Date;var e=a.Event((d.idle?"idle":"active")+".idleTimer");a(c).trigger(e,[c,a.extend({},d),b])},h=function(b){var d=a.data(c,"idleTimerObj")||{};if(("storage"!==b.type||b.originalEvent.key===d.timerSyncId)&&null==d.remaining){if("mousemove"===b.type){if(b.pageX===d.pageX&&b.pageY===d.pageY)return;if("undefined"==typeof b.pageX&&"undefined"==typeof b.pageY)return;var e=+new Date-d.olddate;if(200>e)return}clearTimeout(d.tId),d.idle&&g(b),d.lastActive=+new Date,d.pageX=b.pageX,d.pageY=b.pageY,"storage"!==b.type&&d.timerSyncId&&"undefined"!=typeof localStorage&&localStorage.setItem(d.timerSyncId,d.lastActive),d.tId=setTimeout(g,d.timeout)}},i=function(){var b=a.data(c,"idleTimerObj")||{};b.idle=b.idleBackup,b.olddate=+new Date,b.lastActive=b.olddate,b.remaining=null,clearTimeout(b.tId),b.idle||(b.tId=setTimeout(g,b.timeout))},j=function(){var b=a.data(c,"idleTimerObj")||{};null==b.remaining&&(b.remaining=b.timeout-(+new Date-b.olddate),clearTimeout(b.tId))},k=function(){var b=a.data(c,"idleTimerObj")||{};null!=b.remaining&&(b.idle||(b.tId=setTimeout(g,b.remaining)),b.remaining=null)},l=function(){var b=a.data(c,"idleTimerObj")||{};clearTimeout(b.tId),e.removeData("idleTimerObj"),e.off("._idleTimer")},m=function(){var b=a.data(c,"idleTimerObj")||{};if(b.idle)return 0;if(null!=b.remaining)return b.remaining;var d=b.timeout-(+new Date-b.lastActive);return 0>d&&(d=0),d};if(null===b&&"undefined"!=typeof f.idle)return i(),e;if(null===b);else{if(null!==b&&"undefined"==typeof f.idle)return!1;if("destroy"===b)return l(),e;if("pause"===b)return j(),e;if("resume"===b)return k(),e;if("reset"===b)return i(),e;if("getRemainingTime"===b)return m();if("getElapsedTime"===b)return+new Date-f.olddate;if("getLastActiveTime"===b)return f.lastActive;if("isIdle"===b)return f.idle}return e.on(a.trim((d.events+" ").split(" ").join("._idleTimer ")),function(a){h(a)}),d.timerSyncId&&a(window).bind("storage",h),f=a.extend({},{olddate:+new Date,lastActive:+new Date,idle:d.idle,idleBackup:d.idle,timeout:d.timeout,remaining:null,timerSyncId:d.timerSyncId,tId:null,pageX:null,pageY:null}),f.idle||(f.tId=setTimeout(g,f.timeout)),a.data(c,"idleTimerObj",f),e},a.fn.idleTimer=function(b){return this[0]?a.idleTimer(b,this[0]):this}}(jQuery);

var _firstRun = true;
$(document).ready(function() {
if(_firstRun){
var isLogin = $('#isLogined').val();
var maxIdleTime = 1800000; // 30 mins
var minTimeSession = $("#minSessionTime").val();
var convertMinPopup = 1800000 - minTimeSession;
var minutes = Math.floor(convertMinPopup / 60000);
var seconds = ((convertMinPopup % 60000) / 1000).toFixed(0);
var timerPopUp = minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
document.getElementById('timer').innerHTML = timerPopUp;

	function countDown(){
		console.log("CountDown function called!!!");
		var presentTime = document.getElementById('timer').innerHTML;
		var timeArray = presentTime.split(/[:]+/);
		var m = timeArray[0];
		var s = checkSecond((timeArray[1] - 1));
		if(s==59){m=m-1}
		if(m == 0 && s == 0){
			$("#timeoutContainer").hide();
			logout();  
		}
		document.getElementById('timer').innerHTML = m + ":" + s;
	}
	
	function timer(){
		console.log("calling timer Function!!!");
		setInterval(countDown,1000)
	}
function checkSecond(sec) {
	if (sec < 10 && sec >= 0) {sec = "0" + sec}
	if (sec < 0) {sec = "59"}
	return sec;
}

$( document ).idleTimer(minTimeSession);
$( document ).on( "idle.idleTimer", function(){
	if(isLogin == "true"){
		$("#timeoutContainer").show();
		console.log('before function called!!!');	
		timer();
	}
});


function logout(){
  $.ajax({
      type: "POST",
      url: ACC.config.contextPath + "/logout",
      success: function (response) {
         window.location = ACC.config.contextPath + "/logout";
      }
  });
}

function checkSecond(sec) {
  if (sec < 10 && sec >= 0) {sec = "0" + sec}
  if (sec < 0) {sec = "59"}
  return sec;
}

$("#inactivity_ok").click(function(){
	window.location = window.location;
});
$("#logoutButton").click(function(){
	logout();
});

_firstRun = false;
}

});

Once the page load idle is not getting triggered, please help me to fix the issues.

Thanks

Bower

For some reason when I try to install this component using bower, I don't get a bower.json file, I get a .bower.json file and it has no main in it. What's the name of the component in bower? There seem to be multiple with the same name.

stopping and restarting the timer

I can get my function to start, and I can get it to stop, but I can't get it to restart again after stopping it.

function idlecheck(){
    $(document).idleTimer( 5000 );
    $(document).bind("idle.idleTimer", function(){
        //functionality to occur when idle
        $('#menu').fadeOut(1000);
    });
    $(document).bind("active.idleTimer", function(){
        //functionality to occur when active again
        $('#menu').fadeIn(1000);
    });
}

// start the timer when the doc is ready.
$(document).ready(function(){
    idlecheck();
});

I set up a button to disable the timer.

$('.disabletimer').click(function(x) {
    $(document).idleTimer("destroy");
}

And then one to start it again.

$('.enabletimer').click(function(x) {
    idlecheck();
}

Once the destroy item has been run, i can't start the idle timer at all.

Funny item is that if I don't have the idlecheck run on load, the "enabletimer" button will let make it start.

Is there a better way to pause or stop/restart the timer?

Performance

First of all, everything is my fault. Sorry.

Second of all, I think we can improve the performance of this script. :)

We currently bind to all of these events to judge if a user is active:

events: "mousemove keydown wheel DOMMouseScroll mousewheel mousedown touchstart touchmove MSPointerDown MSPointerMove" 

This makes sense in a way because we really want to know if the user does anything, sure. But…

The key issue here is that in many cases the browser cannot update the UI until the event handler has finished. So the user's scroll, mousemove, or touch is completely held up while it waits for our script to finish before actually getting closer to showing the user the outcome from that interaction.

image

This is described really well in this video:

https://www.youtube.com/watch?v=YyQYhhy1dZI#t=945 watch from 15:45 until 25:00

At the end, you can see a shot of the "show scroll bottlenecks" feature in devtools where this script triggers a bunch:
image

Chrome's touch maestro Rick Byers also gave a long explanation of why touch handlers wreck performance: https://plus.google.com/+RickByers/posts/cmzrtyBYPQc?e=-RedirectToSandbox

touch

The touch events are unnecessary because a touch will end up triggering mousedown anyway.
https://patrickhlauke.github.io/touch/tests/results/ has all the details

the original list:

  • mousemove keydown wheel DOMMouseScroll mousewheel mousedown touchstart touchmove MSPointerDown MSPointerMove

If we remove superfluous events that we can catch with another binding:

  • mousemove keydown wheel DOMMouseScroll mousewheel mousedown touchstart touchmove MSPointerDown MSPointerMove

scroll

Binding to mousewheel, mousescroll is not great, as Nat & Tom offer in that video above. Resig offered similar advice in 2011 (see best practices). A better approach is polling for changes in scrollTop.

page visibility API

it's got great support and is a very simple indicator of "idle", so we could turn off polling then.


So then we're left with..

mousemove keydown wheel DOMMouseScroll mousewheel mousedown touchstart touchmove MSPointerDown MSPointerMove (and a page-visibility-aware scrollTop polling loop)

I think that's a fine list: mousedown mousemove keydown. We won't regress how well we monitor idle/active and we'll speed up all interactions with the pages considerably.

@thorst how does that sound to you?

getElapsedTime Not Working

The following line outputs an object, instead of the elapsed time in ms

console.log($(document).idleTimer("getElapsedTime"));

On startup mousemove is ignored

I'm still experiencing the issue I described in #16 (comment). However now I have had time to investigate what I was experiencing.

Tested on 2/27/2014 with Chrome Version 33.0.1750.117 m && Firefox 27.0.1.

Im testing https://raw.github.com/mikesherov/jquery-idletimer/master/dist/idle-timer.js

Here's how reproduce it.

  1. Refresh the demo page
  2. Immediately begin moving mouse on document, but not textarea. It will pause for what seems to be 3 seconds, then show as an inactive state in #status.
  3. Continue moving the mouse on document but not textarea, without pause, until your arm is tired. It will show as an inactive state in #status.
  4. Stop moving the mouse for at least the timeout time (5 seconds). It will show as an inactive state in #status.
  5. Now move the mouse again, and it shows as active in #status.

Details

The mouse move event is triggered (line 97). obj.idle (line 106) is false, so it never triggers the toggle until the timeout expires once.

I havent tracked it down, but it seems like the textareas timer is triggering for the document timer, and thats why #status shows as idle (step number 2 above)

Issue

This isn't an issue when the timeout is 5 seconds, because it will go in and out of idle state frequently.

But my timeout is high (13 minutes) so for it to perform this cycle, its too late and my server side's session has expired.

Side Note

I thought just setting idle to true or startImmediately to false (or both) would be enough. But the result is the same, after the timeout the banner shows idle even though I'm moving my mouse.

Looking at #1 I believe a fix for that would solve my issue. However, i still need to support ie8, so the proposed fix (pagevisibility) wouldn't work.

Summary

I beleive there are 2 issues:

  1. Textarea timer may be triggering idle on document
  2. Initial activity is ignored until it becomes idle at least 1 time

jQuery 3.x Compatability

I'm currently updating a code base to use jQuery 3.4.1 with the assistance of the jQuery Migrate tool. It is flagging up a deprecation issue within idletimer.

Run the following JSFiddle with the dev tools open and you'll see the warning "JQMIGRATE: jQuery.fn.bind() is deprecated".

http://jsfiddle.net/3x2sqzb1/ (it wouldn't allow direct CDN to idletimer, so I had to paste it for demo purposes).

The instructions advise updating the call from "bind" to "on" - https://github.com/jquery/jquery-migrate/blob/master/warnings.md.

Is this something that can be updated and pushed out so we can continue using this library without risk of it becoming obsolete?

Thanks!

Determine "active" or "idle" on initiation

from dmtr:

The user is assumed to be 'active for the first x seconds', this is certainly true for the document, but not so for the document elements. I guess natural thing to do would be to check if a mouse is 'over' [the document or element] to determine the initial state. If it is - initial state would be 'active', if it is not - 'idle'. That seems to be pretty consistent.

We should probably add an initial callback event to differentiate the immediate idling from the eventual idling.

Event mousemove triggered always

Event mousemove triggered always on plugin change state if using modal window (jquery for example, with overlay) for displaying some popup on idle state.
So if mouse is in document area (even if no mouse moving) so idle state finished without any activity.

I have a patch for this situation:

  1. should remove event 'mousemove' in 'events' variable

  2. after row
    //assign appropriate event handlers
    $(elem).bind($.trim((events + ' ').split(' ').join('.idleTimer ')), handleUserEvent);

we put this code:

    $(elem).mousemove(function (event) {
        if (event.pageX != obj.mX || event.pageY != obj.mY) {
            obj.mX = event.pageX;
            obj.mY = event.pageY;
            //handleUserEvent(elem); - not work for me, so I trigger another event 
            $(elem).trigger('keydown');
        }
    });

wrong repository sorry for this

In my application i have ajax setup to show loader and this is done globally. Issue is that when idle ping the server the loader is showing. My purpose is to set ajax global attribute to false or to be configurable.

Problem with initializing idleTimer with no arguments

When I start the timer and call getLastActiveTime function, getLastActiveTime returns false.
$( document ).idleTimer();
var time = $( document ).idleTimer("getLastActiveTime");

Tracing through the code, it looks like firstParam is undefined. So line 250 skipped over because undefined === null is false, and ends up returning false at line 255.

My current workaround is to call idleTimer(null). In which case, lastActiveTime correctly returns the last active time.
$( document ).idleTimer(null);
var time = $( document ).idleTimer("getLastActiveTime");

Video Listener

This looks like an awesome script.

I need something just like this but if the end user is watching a presentation video we don't want it redirecting. How difficult would it be to add a video listener to this?

Thanks!

autologout demo bug?

For the autologout demo, on lines 147+

 //On mobile js is paused, so see if this was triggered while we were sleeping
if (diff >= session.warningTimeout || warning <= session.minWarning) {
    $("#mdlLoggedOut").modal("show");
} else {

To make sure I understand the code correctly:
Let's say warningTimeout is 10 minutes, and minWarning is 5 seconds.
This will logout the user if they are on a different app for 10 or more minutes, which make sense.
But wouldn't the warning <= session.minWarning logout the user if they went to an app for less than 5 seconds? I think it's supposed to be warning >= session.minWarning.

If am wrong about this, could you please tell me why? Thanks in advance.

V4 Tilling Sprites

Hello,

We are experiencing a new issue with the tilling sprites in PIXI V4.

Here is a fiddle that show the issue : https://jsfiddle.net/sa0zj0vq/1/

When the scale is set to 0.5 (line 6 of the fiddle), holes appear in the repeating pattern. If the scale is set to 1, the issue disappear. We looked into the code of the V4 and we didn't find any difference with our V3 version which works well in this case.

Listen to window blur?

Is it out of scope to listen to and raise events when a users blurs the window.

Example would be:

  • minimizing browser
  • switching tabs
  • Clicking another application
$(window).focus(function() {
    //do something
});

$(window).blur(function() {
    //do something
});

Timeout not being fired in long inactivity periods

I've implemented your timeout workflow based on the autologout demo, and I tried to set it for 30 min. Although it works on desktop, on mobile devices (tested on iPad and iPhone) if you go to the Home screen doesn't work. Any hints on how to make it work with Apple devices properly?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.