0 0 Votes

JavaScript: Show warning when leaving the page

Info by Stefan Trost | 07/11/2016 at 17:07

In this information, I want to show you how to display a warning if the user is about to leave the page. We will use JavaScript for the implementation.

In pure JavaScript (without jQuery), we are using window.onbeforeunload for that:

window.onbeforeunload = function() {
   return 'Do you really want to leave this page?';

With jQuery the same function is looking like that:

$(window).bind('beforeunload', function() {
  return 'Do you really want to leave this page?';

Only show warning if something has been entered

In most cases, a warning is used on pages on which the user has the possibility to fill out a form. However, in this case a warning only makes sense if it is only displayed in case there is really something typed in the form and when the user is about to leave the page via another way than by the form submit button. For example, if the user clicks on the link or the user actually closes the tab on the entire browser.

In order to cover this case especially, we can extend our script accordingly:

var submitted = false;
var userinput = false;
$(document).ready(function() {
  $("form").submit(function() {
    submitted = true;

  $(".userinputs").change(function() {
    userinput = true;
  window.onbeforeunload = function () {
    if (userinput && !submitted) {
      return 'You do not have submitted the form yet.\
      Do you really want to leave this page?';

First, we define the variables "submitted" (has the submit button been clicked) and "userinput" (has the user typed something into the form). After that, we are extending the window.onbeforeunload function by an if condition: the dialog should only be displayed if the variable "userinput" is "true" and "submitted" is "false". Otherwise, the user can leave the website or page without a warning.

We are setting the variables "submitted" and "userinput" to true when the user is clicking the submit button or if the user changes the content of one of the elements with the class "userinputs". Correspondingly, all elements that should be monitored should have assigned this class or you change the script in a way that it directly refers to the name of the corresponding input fields.


About the Author

Avatar AuthorYou can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile | Message


Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own articles on askingbox.com. How to do.