Detect Leaving Visitors with jQuery

April 8th, 2010 - Posted by Steve Marks to Javascript / jQuery, Web Development.

Users leaving your website is never a good thing, but there are some scenarios where you may need to catch them before they head elsewhere on the web as a result of them clicking a link on your site.

Let’s imagine that you want to bring to the users attention the fact they are leaving your website and that you are not responsible for the content of the site they are heading to. This may be particularly useful for websites belonging to legal or pharmaceutical companies, or for sites that display user-submitted URL’s such as directories.

By using jQuery we can quickly and easily detect this scenario. Simply copy and paste the code below anywhere on a page for it to work:

<script src="/jquery.js" language="javascript" type="text/javascript"></script>

<script type="text/javascript">

	// Change this URL to be that of your own website
	var base_url = "";
	var base_url_length = base_url.length;
	$(document).ready(function() {
		$("a").click(function() {

			var link_location = $(this).attr('href');
			// if the link clicked is external
			if (link_location.indexOf("http://")!=-1 && link_location.substr(0, base_url_length)!=base_url) {
				/* DO ACTION HERE */
				alert("You are leaving the website");


Please note, this script does not detect if a user closes the window or leaves your site by another means, such as by going direct to another website by typing it’s URL in the address bar.

This entry was posted on Thursday, April 8th, 2010 at 10:03 pm by +Steve Marks and is filed under Javascript / jQuery, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments (0)
Comments are closed.