Без использования jQuery, только JavaScript:
var inactivityTime = function () {
var time;
window.onload = resetTimer;
// DOM Events
document.onmousemove = resetTimer;
document.onkeypress = 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
}
};
/*call the function*/
<script>
inactivityTime();
</script>
Кредиты: http://forums.devshed.com/javascript-development-115/alert-time-inactivity-click-logout-501444.html
Вы можете добавить больше событий DOM, если вам нужно. Наиболее используемые:
document.onload = resetTimer;
document.onmousemove = resetTimer;
document.onmousedown = resetTimer; // touchscreen presses
document.ontouchstart = resetTimer;
document.onclick = resetTimer; // touchpad clicks
document.onscroll = resetTimer; // scrolling with arrow keys
document.onkeypress = resetTimer;
Или зарегистрировать нужные события, используя массив
window.addEventListener('load', resetTimer, true);
var events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];
events.forEach(function(name) {
document.addEventListener(name, resetTimer, true);
});
События DOM список: http://www.w3schools.com/jsref/dom_obj_event.asp
Не забудьте использовать window
или document
в соответствии с вашими потребностями. Здесь вы можете увидеть различия между ними: В чем разница между окном, экраном и документом в Javascript?