Monday, October 5, 2009

A minimal jQuery source for a fade behind pop-up

I recently wanted to do one of those nice trendy popups that stay within the current web page and fades everything behind the pop-up. I wanted to use it to allow a user to view a demo, a Flash animation. Pretty typical usage from what I've seen.

I figured this was something done handily by jQuery, but I had some trouble finding a minimal, complete source to start with. Everyone seemed to want to force you to go through the tutorial they wrote, step by step. Well, I usually want the code, and then the tutorial.

I found this tutorial which was at least succinct. Soon I had a very small (i.e. minimal), working .html document that behaved how I wanted. For instance, it automatically figures out the horizontal and vertical positioning of the pop-up so it comes up in the center of the screen.

Here you go:
#popup {
height: 100%;
width: 100%;
background-color: #000000;
position: absolute;
top: 0;
#window {
width: 500px;
height: 400px;
margin: 0 auto;
border: 1px solid #000000;
background: #ffffff;
position: absolute;
top: 10%;
left: 15%;
<script type="text/javascript" 
<script type="text/javascript"> 

function Show_Popup(action, userid) {

var hpos = ($(window).height()/2) - (400/2);
var wpos = ($(window).width()/2) - (500/2);
$('#window').css('top', hpos + 'px').css('left', wpos + "px").fadeIn('fast');
// I added a function call here to insert my demo into the #window div

function Close_Popup() {
        <div onclick="Show_Popup()" 
          View demo
<div id="popup" style="display: none;"></div> 
<div id="window" style="display: none;"> 
<div id="popup_content">
<a href="#" onclick="Close_Popup();" >Close</a>

And now for the tutorial, also minimal:

(1) Make sure that the <div id="popup" ... </div> section is placed into your page just prior to the </body> tag.

(2) It's unlikely that your popup height and width will be the same as mine. You'll need to modify in two places to change this - inelegant I know - in the #window style declaration, and in the Show_Popup() function, where hpos and wpos are calculated.

Here's the demo page.

1 comment: