jQuery-Based Popout Ad: Part 3

Published October 1, 2008 by CSS Newbies.

Note: Part 1 of this series is available here, and you can read part 2 here. I’d recommend reading both of those articles before continuing on to this one.

The previous article in this series explained how to take CSS- and XHTML-based advertisement we’d developed and animate it using the jQuery JavaScript library. Today, we’re going to expand our jQuery a bit to make our ad a little bit more user-friendly (if an ad can ever be said to be user-friendly, that is).

We’re going to expand our functionality in two important ways. First, we’ll give the popout a memory: when the user closes the ad, it will remain closed for a predetermined number of days, unless they choose to open it again. And second, we’ll allow the user to open and close the ad by clicking the permanent sidebar cap. And before I get started, I’d like to point out that these two examples are really expandable to countless practical uses — don’t feel limited just because I’m talking about a popout here!

Remembering the User

The only practical way to remember whether the user has opened or closed our ad across multiple visits is by using a browser cookie. I’ve written about setting browser cookies here before, and I’ll be honest – it’s a tedious process writing the code to make the magic happen. However, because we’re already using the jQuery framework, our job is about to get a heck of a lot easier.

jQuery does not come with built-in cookie-setting functionality, which is a rather large shortcoming in my opinion. Luckily, jQuery has a rather active community behind it, and a nice man by the name of Klaus Hartl has released a jQuery cookie plugin. All we need to do is include the link to the plugin in the head of our document, underneath our call to the jQuery library, like so:

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

And voila! Cookies have suddenly gotten a whole lot easier. You’ll see just how easy in a moment.

So how are we going to use these cookies? Well, what makes the most sense to me (and you’re welcome to suggest alternatives) is this: whenever the user closes the ad box, we’ll set a cookie indicating this. If the user opens the ad box again, we’ll delete the cookie. When we load the page, we’ll simply check to see if our cookie is set: if not, we’ll open the ad; if so, we’ll leave the ad closed.

First up, let’s give our cookie a name. For consistency’s sake, I’m going to define the name at the top of my $(document).ready function, along with the other variables:

var popOut = "#popout";
var adBox = "#adbox";
var adWidth = $(adBox).width() + $("#cap").width();
var adCookie = "ad-example";

In this example, I’m calling my cookie “ad-example,” but you could really name it whatever you wanted.

Next, we’ll have to edit our openAd and closeAd functions that we developed in the last article to accommodate the setting and un-setting of cookies. Our openAd function now looks like this:

function openAd() {
	$(popOut).width(adWidth+"px");
	$(adBox).animate({marginLeft: "0"},1200)
	$.cookie(adCookie, null);
}

You’ll note the new line at the bottom. What we’re doing here is calling the cookie function that is included in the plugin we’re using. After the user opens the ad, we look for any cookies named whatever we selected at the top of the document. If one exists, we set it to “null,” effectively destroying it.

Next up, we have the closeAd function:

function closeAd() {
	$(adBox).animate({marginLeft: "-"+adWidth+"px"},1200,"linear",
		function(){ $(popOut).width($("#cap").width() + "px"); }
	);
	$.cookie(adCookie,'closed',{expires: 28});
}

Again, we’re only adding a single line to our code. You can see how easy this is compared to writing your own JavaScript cookie function! This time, after the ad has successfully closed, we’re setting a cookie. We’re giving it a name of whatever we determined at the top of the function (“ad-example,” in our case), giving it a value of “closed,” and setting the cookie to expire in 28 days (four weeks). You could choose whatever duration you felt appropriate here.

And finally, we’ll want to alter the last line in our $(document).ready function, the one that opens the ad when the page loads. The line that opens the ad will now read like this:

if(!$.cookie(adCookie)) {
	$(popOut).animate({opacity: 1.0}, 1500, "linear", openAd);
}

All we’ve done is wrap our animation function in an if statement. If the cookie does not exist (the exclamation point at the beginning of our if statement means “if the following is not true…”), we will execute the animation we built last time. But if there is a cookie set (meaning the user has chosen to close the ad), we don’t animate our ad — meaning it remains hidden off the edge of our page by our CSS.

Developing Click Logic

Next up, we want to alter the click logic on the ad cap — if the ad is closed, a click should open it. But if it’s already open, the ad should close when the user clicks. This increases the odds the user will be able to get rid of the ad when they wish, which is an important usability feature in my mind.

To do this, we’ll need to edit the click function set on our cap. But how do we know if the ad should be opened or closed? Easy: we just set a cookie that will give us the answer we need. If the user clicks on the cap and a cookie is already set, that means the ad is currently closed, so we should open it back up. Otherwise, if no cookie is set, that means our ad is already open. A click at that point should close our ad instead.

Because we went to the trouble of developing functions to open and close our ad, our code change is pretty simple. We just edit the cap’s click functionality like so:

$("#open").click(function() {
	if(!$.cookie(adCookie)) {
		closeAd();
	} else {				   
		openAd();
	}
	return false;
});

All it takes is a simple if-else statement. If the cookie isn’t set, close the ad. Otherwise, open the ad like we would have originally.

And with those changes, we have now developed a popout box that is simultaneously eye-catching and user-friendly. Here’s the JavaScript in its entirety:

$(document).ready(function() {
	var popOut = "#popout";
	var adBox = "#adbox";
	var adWidth = $(adBox).width() + $("#cap").width();
	var adCookie = "ad-example";

	function openAd() {
		$(popOut).width(adWidth+"px");
		$(adBox).animate({marginLeft: "0"},1200)
		$.cookie(adCookie, null);
	}
	
	function closeAd() {
		$(adBox).animate({marginLeft: "-"+adWidth+"px"},1200,"linear",
			function(){ $(popOut).width($("#cap").width() + "px"); }
		);
		$.cookie(adCookie,'closed',{expires: 28});
	}

	$("#open").click(function() {
		if(!$.cookie(adCookie)) {
			closeAd();
		} else {				   
			openAd();
		}
		return false;
	});
	$("#close").click(function() {
		closeAd();
		return false;
	});	
	
	if(!$.cookie(adCookie)) {
		$(popOut).animate({opacity: 1.0}, 1500, "linear", openAd);
	}
});

And you can see a working example of our ad here. If you have any questions, comments, or concerns, please leave a comment and I will do my best to address them.

21 Responses

  1. Pingback: jQuery-Based Popout Ad: Part 1 - CSSnewbie

  2. Pingback: jQuery-Based Popout Ad: Part 2 - CSSnewbie

  3. Billy Wallace (reply)

    The comment I made in Part 1 is not in chronological order!

    Referring to that comment, in Part 2 you do hide the ad but not the cap. If the cap is not hidden then the best solution would be to link to the actual ad image instead of a link to nowhere.

    It looks like your code could be easily modified to allow for pop-down content (Tips, images, etc.) or re-factored for pop-anyDirection but more code would be needed to take care of being to close to the left or right of the view-port.

    Thanks for a well written, progressive and very intuitive article.

  4. Denis (reply)

    Awesome tutorial. Now onto one nit-picky thing… has anyone been able to get this setup working in FIXED position? In other words, the cap/ad scrolls as the user scrolls down the page at a “fixed” position.

    I tried setting ‘position’ property to ‘fixed’ for #popout in the CSS (originally ‘absolute’). That seemed to do the trick until I realized this makes the user not able to click in the area where the ad is supposed to popout!

    Can anyone verify this issue? Any suggestions for fixes?

    Thanks a bajillion! :)

  5. Pingback: » Kullanışlı 9 jquery eklentisi Duymadim.com: Bunudamı duymadın? Araç Bilgisayar Bilim Donanım Fragmanlar Genel Komedi Magazin Müzik Mobil Oyunlar Son Dakika Spor Teknoloji Uzay Video Yazılım İnternet Yeni teknolojiler Yeni telefonlar yen

  6. Mark (reply)

    Nice work but for me I did not like the fact it showed when users had js disabled so here is a little amendment:

    at start of js file add
    add $(“#popout”).addClass(“gotjs”);

    then in the html, in the popout div add,
    class=”nojs”

    finally, in your css file add
    .nojs
    {
    display:none;
    }
    .gotjs
    {
    display:block;!important
    }

    This stops the popout from displaying if the user has no javascript

  7. Pingback: A Simple jQuery Stylesheet Switcher

  8. Pingback: Colorrage Blog » Blog Archive » A Simple jQuery Stylesheet Switcher

  9. Katherine (reply)

    There’s a big piece missing here…. What if the user clicks on the ad? The cookie should remember that action, too, so when they come back they don’t see the popout again.

  10. Pingback: A Simple jQuery Stylesheet Switcher « Why Limit Media

  11. marcin (reply)

    That’s neat. I’ve been looking for something like that for a while. Works like a charm, easy to setup and tweak.
    Huge Thanks!!!

  12. Pingback: A Simple jQuery Stylesheet Switcher | CSS Heaven

    1. Rob Glazebrook (Author) (reply)

      Hi Danielle,

      I don’t see the JavaScript loading anywhere on your page. It’s giving you a “page not found” because it’s following the fake link on the cap instead of firing the JavaScript. :)

  13. Danielle (reply)

    Thanks for the reply :) I’ve added the links to javascript in my header pages – I can see it in the source code also … not sure what else to do!

  14. Pingback: Expandable Banners

  15. Pingback: Looking for a style swicher | BlogoSfera

  16. Pingback: Looking for a style swicher | BlogoSfera

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>