Thought I would go through the steps of creating a one-time popup for a webpage using jQuery. The goal is to create a styled popup that is shown to visitors a single time when they visit a webpage, but not shown on future visits to that pages.
What we will need:- jQuery: Provides the JavaScript framework for the code and does a lot of the heavy lifting
- jQuery Thickbox: Provides the actual popup and gives us an amazing amount of control on whats shown
- jQuery Cookie: Provides the mechanism to track users coming back to the page to prevent them seeing the popup more than once
Getting a webpage ready:
With only few lines of code added the head of a page we can make it ready to handle our popup.
Add into the Head area (between the HEAD tags):
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/jquery.cookie.js"></script>
<script type="text/javascript" src="scripts/thickbox/thickbox.js"></script>
<link rel="stylesheet" type="text/css" href="scripts/thickbox/thickbox.css">
<script type="text/javascript">
$(document).ready(function(){
if ($.cookie('20080521') != '1') {
tb_show("<strong>We're Moving!</strong>",
"#TB_inline?height=190&width=275&inlineId=mypopup","");
$.cookie('20080521', '1', { expires: 20 });
}
});
</script>
What the above does is first make reference to all the components we require to get the One-time popup to work.
The script section:- Checks if the document (page) has fully loaded
- When its loaded it looks for the cookie that is set when the user has viewed the popup. What I did was date code the cookie so you can easily force a popup just by changing the cookie's name
- If the cookie has not be set then a popup is displayed to the user and the cookie gets set with a 20 day expiration
- Each subsequent visit to the page will not trigger the popup because the cookie has been set
Adding the popup:<div id="mypopup" style="display:none">
<p id="msg">
This is a sample popup.
</p>
</div>
This is the hidden content which will be displayed to the visitor as a popup. This can be any HTML code and can contain tables, forms or any styling you want and its location can be anywhere in a page between the BODY tags.
Wrap up:You can see this is a very trivial task when you know the right components to use. With jQuery it couldn't be easier.
Labels: development, javascript, jquery