Archive for the ‘JS/JQuery’ category

A Working Exit Popup

April 3rd, 2010

In this tutorial I’m going to show you how to create an exit popup that has been tested in Internet Explorer 8, FireFox 3, Chrome and Safari 4 (Opera currently does not support the onbeforeunload event).

Traditionally to cause an exit popup you would simply reference a Javascript function in the body tag of your page such as this:

<body onunload="SomeFunction()">

Unfortunately this no longer works as most modern browsers will simply continue to the new destination or close, even if the function has executed. To work with modern browsers you need to assign a function to the OnBeforeUnload prompting the user to stay on the page.

Basic Confirmation Dialog
If you wish to simply ask the user if they wish to leave you can easily assign a function to the OnBeforeUnload directive. This method will prompt the user every time they attempt to navigate away from the page or close the window.

<script type="text/javascript">
     window.onbeforeunload = function() { return "Are you sure you want to leave?"; }
</script>

You may want to ensure that the popup does not occur again such as when they decided to stay on the page. You can do this by making a small modification to your code to alter to the behavior after the dialog is prompted.

<script type="text/javascript">
     var popit = true;
     window.onbeforeunload = function() { 
          if(popit == true) {
               popit = false;
               return "Are you sure you want to leave?"; 
          }
     }
</script>

The above will turn off the popup trigger after the first time the beforeunload event occurs. If the function does not return anything the browser will not prompt the user.

Using JQuery

Sometimes you may want to take some more control over your popup behavior. For example with the above methods, even clicking an internal link on your page will cause the popup to activate. This can be a major turn off to a potential buyer who has opted to continue to the sales page only to be bugged by the dialog. To fix this we can use JQuery.

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
     function PopIt() { return "Are you sure you want to leave?"; }
     function UnPopIt()  { /* nothing to return */ } 
 
     $(document).ready(function() {
     	window.onbeforeunload = PopIt;
		$("a").click(function(){ window.onbeforeunload = UnPopIt; });
     });
</script>

What I did above was create two new functions. One of them executes the popup action and the other does… nothing. We assign the PopIt() function to the onbeforeunload event. However when any anchors, identified by the $(“a”) selector is triggered by a click event, the event is instead assigned to UnPopIt() thus allowing the user to click to their destination without interruptions.

Getting Fancy

So now that we know how to prompt the user to stay on the page, we need to actually do something to capture their participation. Perhaps you would like to offer them the option of signing up for a mailing list for other offers, or maybe entice them with a special deal since the original offer probably did not appeal to them.

We could trigger a popup window, but most browsers have popup blockers built in. We could however utilize some more JQuery goodness and use some Ajax to pop up an internal javascript dialog which is not normally blocked by popup blockers. For this we will use FancyBox a popular JQuery based lightbox script which can be downloaded here.

Fancybox can popup a number of different contents such as images, html code, flash videos as well as iframes. For this example we’ll popup an aweber form to collect the user’s information for a mailing list.

First we’ll want to download Fancybox and add it to our existing code:

<script type="text/javascript" src="jquery.js"></script>
<script src="/fancybox/fancybox.js" type="text/javascript"></script>
<link rel="stylesheet" href="/fancybox/fancybox.css" type="text/css" media="screen"/>
...

Next we will want to create the html dialog for our popup window, you can simply use aweber’s javascript loader.

<div style="display: none;">
	<a id="trigger" href="#aweber">&nbsp;</a>
	<div id="aweber" style="width: 250px; height: 400px;">
		<script type="text/javascript" src="http://forms.aweber.com/form/90/1930283.js"></script>
	</div>
</div>

You’ll notice we also added an anchor with a target the same name as the div’s ID, and that the div we created. Also the div we’ve created is also set to be invisible to the user. The anchor that has been created will act as the trigger for Fancybox. The above code can be placed just before the </body> tag of your site.

Next we need to update our javascript code to trigger the fancybox when the exitpop is initialized.

<script type="text/javascript" src="jquery.js"></script>
<script src="/fancybox/fancybox.js" type="text/javascript"></script>
<link rel="stylesheet" href="/fancybox/fancybox.css" type="text/css" media="screen"/>
<script type="text/javascript">
	function PopIt() { 
		$("a.trigger").trigger('click');
		window.onbeforeunload = UnPopIt;
		return "Would you like to join our mailing list for other offers?"; 
	}
	function UnPopIt()  { /* nothing to return */ } 
 
	window.onbeforeunload = PopIt;
 
	$(document).ready(function() {
	    $("a[id!=trigger]").click(function(){ window.onbeforeunload = UnPopIt; });
 
	    $("a#trigger").fancybox({
			'hideOnContentClick': false,
			'showCloseButton': false
		});
	});
</script>

In the fancybox initialization noted by $(“a#trigger”).fancybox() you can define various attributes of the popup, such as the dimensions (you can match this to your aweber form, with some margin). I’ve also decided to make sure that the popup does not disappear on click and that the close button was not visible. Also we modified the click trigger for anchors in general not to include the trigger so that our fancybox trigger can execute normally.

So there you have it, with the above, when a user attempts to navigate away from your page, the popup dialog will prompt the user on whether or not they’d like to stay (the nice part is most people tend to click ‘ok’ or ‘continue’ when it’s the ‘cancel’ button that allows them to leave). Upon clicking ok, the fancybox popup will trigger showing the aweber form that they can fill out.

On the next page you can see some full-source examples as well as a demonstration and download link.

AJAX with JQuery

August 22nd, 2009

AJAX stands for Asynchronous Javascript and XML, though most people would associate the term with dynamic loading of content without refreshing the browser. I notice that even today a lot of people starting out with AJAX still use the XMLHttpRequest object from scratch that has been around forever.

Traditionally retrieving content with such a method would require no less than something like this:

<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
  {// code for Firefox, Opera, IE7, etc.
  xmlhttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlhttp!=null)
  {
  xmlhttp.onreadystatechange=state_Change;
  xmlhttp.open("GET",url,true);
  xmlhttp.send(null);
  }
else
  {
  alert("Your browser does not support XMLHTTP.");
  }
}
 
function state_Change()
{
if (xmlhttp.readyState==4)
  {// 4 = "loaded"
  if (xmlhttp.status==200)
    {// 200 = "OK"
    document.getElementById('T1').innerHTML=xmlhttp.responseText;
    }
  else
    {
    alert("Problem retrieving data:" + xmlhttp.statusText);
    }
  }
}
</script>
...
<body onload="loadXMLDoc('test_xmlhttp.txt')">
<div id="T1" style="border:1px solid black;height:40;width:300;padding:5"></div><br />
<button onclick="loadXMLDoc('test_xmlhttp2.txt')">Click</button>
...

But with the use of many popular frameworks such as Prototype, JQuery, Mootools, Dojo and others AJAX doesn’t have to be a huge mess for a task so simple. Not only would you get simplicity but better cross browser compatibility as the frameworks take a lot of quirks out of the latest browsers. If a new browser comes out, you can usually just update the framework file to keep all your code compatible.

Here is an example of how the above code could be made simpler with JQuery:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>

Defining a DOCTYPE is very important when dealing with a javascript framework in order to ensure maximum compatibility with most browsers (especially Internet Explorer). I tend to work in xHTML 1.0 99% of the time because I find the best luck with it in a cross browser market. It’s a much stricter document type than HTML 4.01 Transitional, but it tends to work much better.

 
    <script type="text/javascript" src="jquery.js"></script>
 
    <script type="text/javascript">
     $(document).ready(function() {
          $('#T1').load('test_xmlhttp.txt');
 
          $("button.trigger").bind("click", function(e){
               $('#T1').load('test_xmlhttp2.txt');
         });
    });
    </script>
...
<div id="T1" style="border:1px solid black;height:40;width:300;padding:5"></div><br />
<button class="trigger">Click</button>
...

As you can see, not only does JQuery make AJAX loading easy, the selectors are CSS1-3 based making element selection quite easy as well. For folks needing a bit more control on the return data JQuery also has the get(), post() and ajax() functions. More information regarding these functions can be found here : API/1.3/Ajax