The benefits of triggering a popup layover in jQuery over triggering a browser window are numerous.
- All code in one DOM – all control and tracking done in one page environment.
- Less reliance on the client’s browser setting that might adversely affect the popup window. (Blockers, Security settings, etc.)
- No abandoned Popups
- Last but not least – It just looks better
I have noticed the need to create a slick jQuery windowless popup increasingly more often in the past couple of months.
Below is a very basic and bare bones setup for setting up just such a popup which is adapted from Adrián Mato Gondelle’s tutorial on how to create a stunning and smooth popup using jquery.
You can see it action by checking out the jquery-popup demo page
Let’s start off with the HTML elements:
xThis is my popup box
A summary of the elements:
- div (id=”myButton”) – The button to launch the popup
- div (id=”Popup”) – Container for the the popup content
- anchor (id=”popupClose”) – Inside the popup – will close the popup
- h1 tag – Inside the popup – represents the popup content
- div (id=”bgPopup”) – a dive that will place a shaded background behind the popup over the rest of the elements on the page
Now lets include some CSS:
/*
#popupClose - this is referring to the anchor tag inside the popup conatainer.
We'll absolute position and style it here
*/
#popupClose{
font-size:20px;
line-height:20px;
position:absolute;
right:6px;
top:4px;
font-weight:700;
display:block;
}
/*
#bgPopup - this is referring to the element that will cover the whole page
behind the popup and above the rest of the page.
NOTE: if you are using z-index on the same level in the DOM -
#bgPopup z-index needs to have the second highest value (behind #Popup)
*/
#bgPopup{
display:none;
position:fixed;
_position:absolute; /* hack for internet explorer 6*/
height:100%;
width:100%;
top:0;
left:0;
background:#000000;
z-index:1;
}
/*
#Popup - The popup container
NOTE: if you are using z-index on the same level in the DOM -
#Popup z-index needs to have the highest value.
*/
#Popup{
display:none;
position:fixed;
_position:absolute; /* hack for internet explorer 6 */
background:#FFFFFF;
border:2px solid #cecece;
z-index:2;
padding:12px;
font-size:13px;
}
/*
#myButton - The Button.... make it have Button-like properties
*/
#myButton{
display:block;
position:relative;
width:200px;
height:50px;
line-height:50px;
font-family:"Trebuchet MS";
font-size:14px
text-align:center;
}
Now we just need to add the functionality to the page.
Note: this code assumes there is already an inclusion of a jQuery Library.
Javascript functions:
function loadPopup(){
//loads popup only if it is disabled
if($("#bgPopup").data("state")==0){
$("#bgPopup").css({
"opacity": "0.7"
});
$("#bgPopup").fadeIn("medium");
$("#Popup").fadeIn("medium");
$("#bgPopup").data("state",1);
}
}
function disablePopup(){
if ($("#bgPopup").data("state")==1){
$("#bgPopup").fadeOut("medium");
$("#Popup").fadeOut("medium");
$("#bgPopup").data("state",0);
}
}
function centerPopup(){
var winw = $(window).width();
var winh = $(window).height();
var popw = $('#Popup').width();
var poph = $('#Popup').height();
$("#Popup").css({
"position" : "absolute",
"top" : winh/2-poph/2,
"left" : winw/2-popw/2
});
//IE6
$("#bgPopup").css({
"height": winh
});
}
Time to tie it all together with functionality!
We’ll use the jQuery ‘.ready’ function to assign the functionality to the objects on document ready:
$(document).ready(function() {
$("#bgPopup").data("state",0);
$("#myButton").click(function(){
centerPopup();
loadPopup();
});
$("#popupClose").click(function(){
disablePopup();
});
$(document).keypress(function(e){
if(e.keyCode==27) {
disablePopup();
}
});
});
//Recenter the popup on resize - Thanks @Dan Harvey [http://www.danharvey.com.au/]
$(window).resize(function() {
centerPopup();
});
And that’s it.
Great Tutorial!!! I’m new to juery, and I was looking for an easy popup window technique. One question though, what does .data(“state”) do. I haven’t run into .data() yet, and I am a bit confuse.
Thank so much for the tutorial
Thanks for the Comment Bradley! The data function in jQuery allows you to attach a variable to an element in the DOM.
So what I am doing here in this code is keeping track of the state of the overlay background. On the background element I am assigning a variable “state” and changing the value to 1 when the overlay is active and 0 when it is not. This allows us to check the state before triggering and vice versa.
There are a lot of different ways to accomplish the same thing. We could have used a global variable to keep track of the state, or we could run a CSS check (If the Background Popup is visible.. ). I went the route of data() for this tutorial to keep it in jQuery, and not leak out a global variable.
Here is the doc on data… http://api.jquery.com/jQuery.data/
Thanks again!
Thanks for this tutorial… good stuff. I’m using some of this code on a site, but imho it also should call the center function on resize, eg:
$(window).resize(function() {
centerPopup();
});
Also, not quite sure why (I’m looking into it still) but it doesn’t center perfectly, it goes slightly low and to the right. Any thoughts?
Hey Dan – thanks for the Comment. I agree with you – Calling the centerPopup function on resize is a money idea. I have added it to the code above and the sandbox page.
As far as why your box isn’t centering perfectly – without looking at the code – I am willing to bet it is because the #Popup isn’t placed on the window level. The Popup div will center to its parent container. If you have the #Popup div in a container element that isn’t centered perfectly – then the Popup will appear off center.
I hope that helps!
[...] [...]
Thank you, Joel! Great script! Almost what I’m looking for! I’m aiming to trigger the pop up automatically on various user agents and show alternative contents per agent (e.g. for driving attention to a mobile app available for the respective platform). However as it’s been literally eons since I’ve touched ecma/js, perhaps you could point me in the right direction?
I guess I’ll be using something like an if statement with a user agent check on document ready?
$(document).ready(function() {
if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPad/i)) || (navigator.userAgent.match(/iPod/i))) {
something.something(“something”);
}
Thank you in advance!
Hey Vidar- You could definitely incorporate a check of the device using navigator.userAgent.match.
As far as incorporating with the above code – The cleanest merge might be to load content into the popup div.
I didn’t test this.. but it could look something like this:
//Place external files on the server for each iteration of content. [iphone.html, ipad.html, android.html..]
//Create a string variable myContent based off your user agent match test and assign the value of the URL for this specific content of this device.
//Now pass it into the loadPopup function
function loadPopup(myContent){
//loads popup only if it is disabled
if($("#bgPopup").data("state")==0){
//Empty the popup window
$('#Popup').empty();
//Load the Content
$('#Popup').load(myContent, function(){
//On success perform the following:
//Prepend the close button back in (removed on .empty)
$('#Popup').prepend('x');
//Fade it in
$("#bgPopup").css({
"opacity": "0.7"
});
$("#bgPopup").fadeIn("medium");
$("#Popup").fadeIn("medium");
$("#bgPopup").data("state",1);
});
}
}
Wow! Neat! That’s just what I’ve been looking for.
One question: how can I get #Popup to appear, say, 150 pixels from the top (still horizontally centered)?
(I’m thinking the answer lies somewhere in the javascript section.. and, yes, I’m a bit of a dullard
)
Thanks!
For the positioning of the popup window you are going to want to focus on the centerPopup function. This is where we set the ‘top’ css attribute – which sets the vertical position. Currently we set the top equal to 1/2 of the height of the window subtracted by 1/2 the height of the popup resulting in the popup being centered vertically.
To achieve what you are looking for you could modify the function to look something like:
function centerPopup(){var winw = $(window).width();
var winh = $(window).height();
var popw = $('#Popup').width();
$("#Popup").css({
"position" : "absolute",
"top" : "150px",
"left" : winw/2-popw/2
});
//IE6
$("#bgPopup").css({
"height": winh
});
}
Hey Joel ,
It’s a great tutorial , something that I can use to display my results over an Ajax call , but when I just try to run the code and click the button , nothing happens. I have seen that there are no errors in firebug too.
Can you suggest me what should I do ?
P.S : I am including jquery-1.3.2.min.js library .
Thanks
Hi! Thanks for sharing this. Works great! What’s the easiest / best way to add multiple popups on one page? Thanks!
Hi Kim,
Well this tutorial is more tailored to just one instance of a popup to show how it works. If you want to start incorporating multiple popups than I would recommend altering the code to allow for passing of the jQuery object.
So quicky editing the above the javascript might look something like this:
function loadPopup(bgPop, popWin) {
if(bgPop.data(“state”)==0){
bgPop.css({
“opacity”: “0.7″
});
bgPop.fadeIn(“medium”);
popWin.fadeIn(“medium”);
bgPop.data(“state”,1);
}
}
function disablePopup(bgPop, popWin){
if (bgPop.data(“state”)==1){
bgPop.fadeOut(“medium”);
popWin.fadeOut(“medium”);
bgPop.data(“state”,0);
}
}
function centerPopup(bgPop, popWin){
var winw = $(window).width();
var winh = $(window).height();
var popw = popWin.width();
var poph = popWin.height();
popWin.css({
“position” : “absolute”,
“top” : winh/2-poph/2,
“left” : winw/2-popw/2
});
//IE6
bgPop.css({
“height”: winh
});
}
$(document).ready(function() {
$(“#bgPopup, #bgPopup2″).data(“state”,0); //You can probably use the same BG for all popups – but just to show how to use more than one.
$(“#FirstButton”).click(function(){
centerPopup($(“#FirstPopup”),$(“bgPopup”));
loadPopup($(“#FirstPopup”),$(“bgPopup”));
});
$(“#FirstPopupClose”).click(function(){
disablePopup($(“#FirstPopup”),$(“bgPopup”));
});
$(“#SecondButton”).click(function(){
centerPopup($(“#SecondPopup”),$(“bgPopup2″));
loadPopup($(“#SecondPopup”),$(“bgPopup2″));
});
$(“#SecondPopupClose”).click(function(){
disablePopup($(“#SecondPopup”),$(“bgPopup2″));
});
$(document).keypress(function(e){
if(e.keyCode==27) {
disablePopup($(“#FirstPopup”),$(“bgPopup”));
disablePopup($(“#SecondPopup”),$(“bgPopup2″));
}
});
});
Hi, I attempted to follow the logic here but the multiple links do not work (meaning it does do anything when clicked). Wonder what could be the issue…
Without seeing the code I am really not sure. A good place to start looking is the JavaScript error console in your browser.
Hi there. Thanks for the tutorial!
One issue I found. I have placed a YouTube video inside the popup and it works fine.
However, if you close the window, the video keeps playing. You have to open again and pause.
Is there a way to kill the content once you click in “close”?
Thank you for your time!
Ahh.. right. You will need to remove the content element from the DOM to achieve what you’re looking for.
You’ll have to add
$("#Popup").empty();to the disablePopup function – next to the fadeOut. This removes all of the content from the popup.
Of course, in so doing, you will need to add the content back into the popup on load otherwise the popup will be empty on the second click.
so you would want to add
$("#Popup").html('The HTML Content for the popup window');to the loadPopup function
To avoid having your code written twice (once in the Popup Div and once in the JavaScript) you can simply empty the popup div in the HTML as the loadPopup is going to replace your content with the HTML you’ve specified in your JavaScript anyways. If you take this approach the popup will work as expected – but it won’t be centered on the screen. Currently, the way the code was written, The popup is centered based on it’s width and height before the popup is displayed resulting in a zero value for both width and height.
So to chase this rabbit all the way back into its hole – the centerPopup call should just be moved into the loadPopup function and removed from the click action. The final loadPopup function would look something like:
function loadPopup(){
//loads popup only if it is disabled
if($("#bgPopup").data("state")==0){
$("#bgPopup").css({
"opacity": "0.7"
});
$("#Popup").html("The HTML Content for the popup window");
centerPopup();
$("#bgPopup").fadeIn("medium");
$("#Popup").fadeIn("medium");
$("#bgPopup").data("state",1);
}
}
Hope that helps!
Hi Joel,
Thank you for your time! Really appreciate.
I’ve implemented as you mentioned above and it works great.
However
now the close button doesn’t work when clicked. The function disablePopup() works when you press ESC but not when you call the same function by clicking.
I had to move the close button inside the div in the JavaScript so it appears when the window pop up.
Anyway, I’m not expert in JavaScript but I’m trying to figure out myself.
If you happen to know the answer and have some free time to help, it would be great!
Thank you!
Junior
New Zealand
I can see why – In writing it down and not trying it – it never occured to me that when I empty the popup I am also removing the close button. I can see how that might be a useful thing to have… haha.
Check out this live demo to see how this code can be modified to remove content on close and re-added on opening:
http://jsfiddle.net/yfnGg/
Brilliant man…! Finally, a technical tutorial that is not complex and does not assume the reader is also a Sr. Web Developer!
Thanks!!
Thanks so much for keeping this simple, straight forward and easy to follow. This worked great right away!
Thanks very much!
Hi Joel, nice plugin but I have a question (request):
How may I use this popup to appear automatically after 3 seconds after a user visits my home page (once loaded) appear once per day?? What I want is to show a popup that displays a newsletter sign up form box.
Hi Gabriel – As far as getting the popup to load 3 seconds after a page load you could put something like “setTimeout(function(){loadPopup()},3000);” in a $(document).ready() call. As far as doing it once a day you could simply check for a cookie to exist. if doesn’t exists you create the cookie, set an expiration of 24 hours – and fire the above code. Here’s a little tid-bit on using cookies in javaScript. Hope that helps!
Hey Joel,
It’s a great tutorial.Thanks for keeping this simple, quick to follow. Worked right away.
Hi there
Great tutorial, working well, but when I try to push the button in the pop-up window, nothing happens.
Can anyone help please?
Thanks
Thanks for your post, really its work.
Awesome tutorial, can’t beleive I didn’t come across it sooner. One question! How can I make the popup occur on page load rather than use a button?
Cheers!
This is awesome! Thank you! Is there a way to have a text link to open the pop-up instead of a button?
Great Work Joel !!