[Code] Visitor Leave Page Warning

jquery visitor leave page warning

I do freelance web development from time to time (because I love coding but only get the opportunity to plan and strategize by day as a digital project manager), so I was thrilled to hop into some code on my first morning off work during the holiday break. As I frequent industry forums, I connected with someone who was looking to better convert his web traffic by displaying a warning to visitors before leaving the page.


In most websites, in this case affiliate marketing websites, visitors are most valuable to the owner when they convert (do some type of action whether it be a purchase, contact form completion, etc). The affiliate marketer I was speaking with wanted to confirm that the visitor wanted to leave the page if they clicked another link or closed the window, but only wanted that message to display if they had not filled out the contact form on the page.


I threw together a quick but effective solution using the jQuery JavaScript framework. I likely don’t need to make mention of jQuery because it is so well known, but do make sure you have it included on your site before you implement the code below.

The Code

var skipNag = false;

$(document).ready(function() {
    $('#form').submit(function() {
          skipNag = true;

$(window).bind('beforeunload', function(){
    if(skipNag == false){
        return('Are you sure you want to leave this page?');

How It Works

  1. Line 1 creates a variable named “skipNag” which is later used to determine whether the visitor will be prompted with the pop-up alert. We defaulted this variable to false, so that in most cases the message will not be skipped – and therefore displayed to the visitor.
  2. Lines 3-7 check if the form (whose ID is “form”) is submitted. If the form is being submitted, we set the skipNag variable to “true”, because we do not want the visitor to see the pop-up alert.
  3.  Lines 9-13 monitor the event when the page is about to change (go to a different URL or the window is about to close).
  4. Line 10 reads the “skipNag” variable we set, and if the variable is “false” (which it is by default), the website will present a message which reads “Are you sure you want to leave this page”?

Download & Demo

  1. You may view the live demo
  2. And you can download the full source code


Let me know in the comments if you found this helpful, or if you have any questions. This is one of a few ways to tackle the problem, but it’s pretty effective given that it does so much with only a few lines of code.

Tagged with: ,
Posted in Code

Warning: count(): Parameter must be an array or an object that implements Countable in /home/wesleyal/public_html/blog/wp-includes/class-wp-comment-query.php on line 405