Kyle Boyd
Kyle Boyd

Reputation: 11

Display a message if a button isn't clicked for a certain period of time

How could I display a message after checking if a specific button wasn't clicked within a period of time (i.e. 20 seconds) using jQuery?

I already have a functional example which displays a message if the mouse stays idle after 30 seconds right here

Thanks, Kyle

Upvotes: 1

Views: 293

Answers (3)

joequincy
joequincy

Reputation: 1395

When you start the timeout, assign the ID it returns to a var:

function visible_a_message(){
  $('#warningMessage').show();
}
var timeout = 20000; //20 secs
var showWarningBox = setTimeout(visible_a_message, timeout);

Then when the button is clicked, clear that timeout:

<input type='button' onClick='clearTimeout(showWarningBox);'" />

This does not rely on the assumption that the button will take the user to a different page (it does cancel showing the message after the button has been clicked, no matter what the browser is doing) and it skips the cruft of using classes as variables.

Upvotes: 1

Tomalak
Tomalak

Reputation: 338148

$(function () {
  var pageLoaded = new Date();

  $("#preventButton").click(function () {
    // mark as clicked only within 20 seconds after page load
    if (new Date() - pageLoaded <= 20000) {
      $(this).addClass("clicked");
    }
  });

  setTimeout(function conditionalMessage() {
    // show a message if #preventButton had not been marked as clicked
    if ( !$("#preventButton").is(".clicked") ) {
      alert("a message appears");
    }
  }, 30000);
});

Upvotes: 0

Serg
Serg

Reputation: 606

from your page source I would use something like this:

setTimeout(function(){
    $("#idletimeout").slideDown(); // show the warning bar
  },20000 //20 seconds
)

so whenever user do on that page he will see warning box unless he clicks on the button (leave the page actually)

Upvotes: 0

Related Questions