Javascript, popular, Tutorials

Easy Javascript/AJAX Exit Pop up script – Creates div overlay on page exit

Update 1-28-2012 – Works! Fixed Chrome Image Issue – It is now working in All Browsers

So the other day a client requested that when a visitor leaves any page on the site, they be greeted by an alert (such as ‘alert(‘this is your alert’);’) and if they click ‘Cancel’ they then go to an alternate ‘Exit Pop’ page that acts as a last ditch effort page to salvage a sale, or an opt-in, or dignity, what have you. Otherwise they just click ‘OK’ and go on their merry way in the opposite direction.

Usually I would just grab code from another page that I had done something similar on, but If you have ever dealt with old code before, You have either forgotten exactly what you needed to change in order for it to work ‘out of the box’ for your new situation, so you end up wasting about 10 minutes testing to get it right.

So I decided to streamline the process once and for all!

I had searched around the Googleverse for a similar simple script, but could not find an easy to use one that was contained in basically one easy to use file that did not include a kitchen sink of un-needed features.

I will try to explain my code. So here we go:

First, the page you want the action to happen on, in our case, is index.php

This is the only important bit of code needed on that page.

<script type="text/javascript" src="scripts/as_exitPop.js">
* Easy Javascript/PHP Exit Pop up script @ Developer's Blog (
* This notice MUST stay intact for legal use
* Visit @andysowards at for full updated source code

This is of course the code that includes the .js file(which will do all of our work) and will of course preserve my copyright information(which is creative commons, so basically you can do whatever you want with it, but please give me credit for it.). I usually place this code before the ending tag, but I have not tried it in the head code. Give me feedback if you try it that way!

Next is the actual .js file, which is called ‘as_exitPop.js’ and is located in the ‘scripts’ folder:


var ExitPopURL = ''; //This is the URL where your 'exit page' is located.

/* NOTE: If you experience an error it is most likely due to the strict AJAX security, make sure that you are accessing the correct URL, for example, if you have in your browser, and in the 'ExitPopURL' then there will be a conflict. they must both match. .htaccess to ensure that your visitors are visiting www. is good practice here.*/

var AlertBox = "*****************************************************\n\nWait! Stop! Don't Go!\n\nBefore leaving, please leave a comment on the \n\nscript post and share your suggestions.\n\nThanks for visiting\n\nAndy \n\n*****************************************************";

// This is what the alert() pop up verbage says.

//DO NOT EDIT BELOW This LINE (Unless of course your Savvy!) ------------------------------

There is more to this .js file of course, but for the moment, this is all you really need to worry about.

First you see a var called ‘ExitPopURL’ and Hopefully is self explanitory to what it is. all you have to do is edit this in the .js file to be the url that points to your ‘exit pop’ page. Which means this is the page that will be seen if the user chooses to give you a ‘second chance’.

Second, you see a variable called ‘AlertBox’, Again, hopefully self explanitory, but this is the variable that contains the text that will be seen in the javascript pop up alert box. You can change this to any verbage you would like.

Now for the next bit of code:

window.onload = function(){
// this is where we start our journey...
}// end function onunload

What is happening here is that the createExitPop(); function(which is declared next) is running when the browser first loads the page. So basically when the page loads, your exit pop is hiding, like a tiger, waiting for someone to try and leave.

Next is your basic AJAX function, I will not explain this here because there are countless references and explanations of AJAX elsewhere:

function ajaxGET(divId, page, effect)
var xmlHttp;
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
// Internet Explorer
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
alert("Your browser does not support AJAX!");
return false;

if(effect == 'collapse') { document.getElementById(divId).style.display='none'; }
else { document.getElementById(divId).innerHTML=xmlHttp.responseText; }

Next, Lets declare that createExitPop function:

function createExitPop()
var theBody = document.getElementsByTagName('body')[0];
var newdiv = document.createElement('div');
newdiv.setAttribute('style', 'width: 100%; height: 100%;');

// put div on page

//add exit pop to page (contents are from your exit.php(or whatever you named it) page)
document.getElementById('ExitDiv').value = ajaxGET('ExitDiv', ExitPopURL);

// style exit pop to resemble its own page
document.getElementById('ExitDiv').style.display = "none";
document.getElementById('ExitDiv') = '0px';
document.getElementById('ExitDiv').style.left = '0px';
document.getElementById('ExitDiv').style.position = 'relative';
document.getElementById('ExitDiv').style.backgroundColor = '#FFFFFF';

}// end createExitPop

Here we are taking the body tag, assigning it to the ‘theBody’ variable and then setting an attribute to reference it, in this case we are setting the id of ‘body’.

Then we are creating a whole new div and calling the variable holding it ‘newdiv’. We then do the same thing with the new div that we did with the body tag, and add an attribute, an id of ‘ExitDiv’.
We also set some styles for our new div, in this case we set the width and height.

We then append the new div child to the body of the document. Once our new ‘ExitDiv’ is in the document, we can reference it using the DOM. We are using AJAX to inject our ‘exit.php’ contents into the div using the variable ‘ExitPopURL’ as the reference for content.

We then just add some styles and customize our ExitDiv.

We are almost done, Here is where the magic happens!

isExit = true;

function ExitPop(isExit) {
if(isExit != false) {
isPop = true;

var bodyTag = document.getElementById? document.getElementsByTagName("BODY")[0] : document.body;

// add id="body" so that it can be referenced.
bodyTag.setAttribute("id", "body");

//replace body text with exit pop
bodyTag.innerHTML = document.getElementById('ExitDiv').innerHTML;
return AlertBox;
} // end if
}// end function

window.onbeforeunload = function(){

// Lay down an exit pop!!
return ExitPop(isExit);

}// end function onunload

Here we set the variable ‘isExit’ to true. Why? Because if they try to do anything other than access an ‘isExit=false’ tagged link or form, then they are trying to leave the page! And we cant have that now can we? Of course not.

Inside the ExitPop function its parameter is the ‘isExit’ variable, it is evaluating whether or not it is true or false. If true, then the function replaces whatever is in the body tag with the inner HTML of the ExitDiv, which in turn makes the page have the content of your ‘exit.php’ page. An alert then pops up asking the user what they want to do, and you select the copy that goes in there using the ‘AlertBox’ variable.

Then, with the magic of the window.onbeforeunload method, before the window loads another page, it calls our ExitPop function and references the current state of the ‘isExit’ Variable.

Once the alert pops up, If they choose ‘OK’ they go. If they choose ‘Cancel’ they stay. Simple right?

Lastly, the only thing left is to make your ‘exit.php’ page look however you want! and the page will replace the with whatever is in your ‘exit.php’ file, and of course you can name the ‘exit.php’ file whatever you want.

One last note, if you have navigational links on your page that need to NOT trigger the exit pop functionality, simply add this attribute to the link ‘onClick=”isExit = false;”‘ or if you are using a form, then it would be ‘onSubmit=”isExit = false;”‘ and you should sneak past the security and on to the desired page :).

Hope you enjoy this and it helps save you time or make you money, and if you run into any trouble or have suggestions on making it better, let me know and I will implement the good ones!

For a Live Demo Example Click Here.

To download the original source code click here Easy Javascript/AJAX Exit Pop up script

Did this script help you? Donate to make it even better!

Was this helpfull? Want to Buy Me A Beer?

This script has received a LOT of feedback, Thanks everyone! in order to keep it up to date and make it even better, your donations are appreciated!!

* Please contact me if you would like to pay me for a custom script to meet your needs or help on your current or future Web Development project.

Please note: you have to have web hosting for this technique to work, some free sites like Myspace or similar do not allow the use of javascript. If you want to host your site yourself and use this technique to capture leads, then you can pickup some cheap web hosting and set it up.

You Might Also Like