3

I have this code to do this task: if no activity from user (mousemove and keypress) for 10 seconds then display a dialog (Jquery UI dialog) to warn and let user know they will be redirected to another page in the next 5 seconds unless they do something. How do I make the "5" in "You will be automatically redirected to ... after 5 seconds." to be counting down as 5, 4, 3, 2, 1 => then redirect ?

<script>
        // Set timeout variables.
        var timoutWarning = 10000; // Display warning in 10 seconds.
        var timoutNow = 15000; // Timeout in 15 seconds
        var logoutUrl = 'http://google.com'; // URL to redirect to.

        var warningTimer;
        var timeoutTimer;

        // Start timers.
        function StartTimers() {
            warningTimer = setTimeout("IdleWarning()", timoutWarning);
            timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
        }

        // Reset timers.
        function ResetTimers() {
            clearTimeout(warningTimer);
            clearTimeout(timeoutTimer);
            StartTimers();
            $("#timeout").dialog('close');
        }

        // Show idle timeout warning dialog.
        function IdleWarning() {
            $("#timeout").dialog({
                modal: true
            });            
        }

        // redirect the user.
        function IdleTimeout() {
            window.location = logoutUrl;
        }       

    </script>

html

<style>
    #timeout {
        display: none;
    }
</style>
<body onload="StartTimers();" onmousemove="ResetTimers();" onclick="ResetTimers();">
<form id="form1" runat="server" defaultbutton="DoNothing">
    <asp:Button ID="DoNothing" runat="server" Enabled="false" Style="display: none;" />
    <div class="page-container">
        <div class="container">

            Hold your mouse and don't press any key for 10 seconds, an dialog alert will be displayed.
            <div id="timeout">
                <h1>Session About To Timeout</h1>
                <p>
                    You will be automatically redirected to google after 5 seconds.<br />
                    To stay on this page move your mouse or press any key.
                </p>
            </div>

        </div>
    </div>
</form>

Ronaldinho Learn Coding
  • 13,254
  • 24
  • 83
  • 110

2 Answers2

1

You can use jquery-idleTimeout

Here is the demo

Usage example:

 $(document).ready(function(){
           $(document).idleTimeout({
             inactivity: 10000, 
             noconfirm: 5000,
             dialogTitle: 'title',
             dialogText: 'warning text',
             redirect_url: 'http://google.com',
           });
          });

Edit:

To add countdown functionality, you can use jquery-idle-timeout

It has onCountdown event. Here is the working example.

Vano Maisuradze
  • 5,829
  • 6
  • 45
  • 73
1

Vano's suggestion of a jQuery plugin is good, and there's no reason not to use that. If you want to do it yourself, though, the code should be pretty simple:

var timer = -1; //so the timer doesn't start until everything is rendered

setInterval(function() {
    timer--;
    if (!timer) {
        window.location = logoutUrl;
    } else if (timer <= 5) {
        $('#timeout').html("Redirecting in " + timer + " seconds");        
    }
}, 1000);

$(document).on('ready keypress mousemove focus click scroll', function() {
    timer = 15;
});

Working example: http://jsfiddle.net/jvvgepo4/

Justin Morgan - On strike
  • 30,035
  • 12
  • 80
  • 104
  • I'd love to use that plugin but problem as I commented in his answer was it only give the option to continue staying by clicking to the button, where I want when user move mouse/click mouse or use keyboard they can stay as well. Your code is simple and works better, it also avoid the `` => this make the `ResetTimers()` stopped working after the JqueryUI dialog appeared for the first time, meaning the dialog keep appearing after 10 seconds no matter what you do. – Ronaldinho Learn Coding Apr 21 '15 at 16:47
  • what `$(document).on('ready keypress mousemove focus',` does and `if (!timer)` means what? – Ronaldinho Learn Coding Apr 21 '15 at 16:48
  • another question, when the time is up, the page is not redirecting immediately but it closes the JqueryUI dialog first and then redirect, how do I make it redirect on-time while the dialog is still open (like this: http://www.erichynds.com/examples/jquery-idle-timeout/example-dialog.htm)? – Ronaldinho Learn Coding Apr 21 '15 at 16:55
  • 1
    It means that the timer starts when the page loads (`ready`), resets itself every time someone presses a button (`keypress`), moves the mouse (`mousemove`), or selects a form field (`focus`). `focus` is probably redundant, but it shouldn't hurt anything. I'm just unsure of how well this will capture touch events on a mobile device. You might want to test it on a phone and maybe add some more events. – Justin Morgan - On strike Apr 21 '15 at 16:56
  • `window.location = logoutUrl` should make it redirect immediately. Is that not happening? By the way, I edited the list of events to include `click` and `scroll`. Again, possibly redundant, but it won't hurt. – Justin Morgan - On strike Apr 21 '15 at 17:01
  • this, I am making a gif image that shows you the problem. Basically it close the dialog first so you basically go back to the page then it redirect (even it quick but still noticeable). In here you can see the page redirect immediately while the dialog is still open: http://www.erichynds.com/examples/jquery-idle-timeout/example-dialog.htm – Ronaldinho Learn Coding Apr 21 '15 at 17:10
  • Here the the HTML demo: http://pastebin.com/ckZiLAJp you can see it yourself of what I mean, it always close the dialog first before redirecting to other page. – Ronaldinho Learn Coding Apr 21 '15 at 18:00
  • When I tested it in my browser, redirecting to google.com violated the [Same-Origin Policy](http://en.wikipedia.org/wiki/Same-origin_policy). Try running it with your JavaScript console open to see any errors. If you get a "cross-origin policy" or similar error, try some of the workarounds in [this answer.](http://stackoverflow.com/a/3076648/399649) – Justin Morgan - On strike Apr 22 '15 at 15:10