kemosabe
kemosabe

Reputation: 154

Popup after user has been idle

I have written some code that brings up a message for the user to either ignore the message or go to another page if they have been idle for more than a minute. Everything works, as I want it to except when the user ignores the message. Here is my code:

if ( valid ) {
    var idleTime = 0;
    jQuery(document).ready(function () {
    var idleInterval = setInterval(timerIncrement, 60000);
});

function resetTimer() {
    idleTime = 0;
}

jQuery(document)
.on('mousemove', resetTimer)
.on('keydown', resetTimer)
.on('scroll', resetTimer);

function timerIncrement() {
    idleTime = idleTime + 1;
    if (idleTime >= 1) {
        jQuery('#popup').show();
    }
    jQuery(window).unbind();
}

jQuery('#popupClose').click(function() {
    jQuery('#popup').hide();
});
}

I want the popup to not repopulate after they click #popupClose.

Upvotes: 0

Views: 620

Answers (2)

relief.melone
relief.melone

Reputation: 3322

I'd do it like this. Just define a start time when you initialize your script. Let an interval run that checks how much time has passed. If it's more than your time wished show the dialog. if not hide it. Also reset the timer on your events. Your javascript will look like this

$('#btclose').on('click', function(){
    clearInterval(interv);
  $('#popup').hide();
});
var start = new Date();

var interv = setInterval(function(){
    var now = new Date();
  console.log()
  if(now-start > 5*1000){
    $('#popup').show();
  }

},10);


$('body').on('mousedown click mousemove', function(){
    start = new Date();
});

Here's my fiddle

https://jsfiddle.net/c2L7wpn3/8/

Seems to work. Let me know if this helps

Upvotes: 1

Unamata Sanatarai
Unamata Sanatarai

Reputation: 6637

You can either store the information in a cookie, or with a flag (depending on whether you want the popup on each pageview or only once, period).

Then, check the flag/cookie before the showing of the popup. For example:

function timerIncrement() {
    idleTime = idleTime + 1;
    if (idleTime >= 1) {
        if (jQuery('#popup').data('closed') == 1){
            jQuery('#popup').show();
        } 
    }
    jQuery(window).unbind();
}

jQuery('#popupClose').click(function() {
    jQuery('#popup').data('closed', 1);
    jQuery('#popup').hide();
});

Upvotes: 0

Related Questions