Popup Tutorial

How to Create an Overlay Popup Box Using HTML, CSS, and jQuery

popup_tutorial

Have you ever wondered how to some websites create an overlay popup when they click on a link or button? Perhaps you are wondering how to create an error overlay or even a simple ad popup (not recommended since those are really annoying). Well you’re in luck. I’ll break down the basic HTML structure, CSS, and JavaScript/jQuery code as well as explain the process behind the popup overlay.

Basic HTML Structure

Here’s the basic HTML structure that we’ll use to design the popup.

[HTML]
<html>
<head>
<meta content=”width=320px, initial-scale=1, user-scalable=yes” name=”viewport” />
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js”></script>
<script type=”text/javascript” src=”custom.js”></script>
<link type=”text/css” rel=”stylesheet” href=”stylesheet.css” />
</head>
<body>

<div class=”main-content”>
<!– Your Content Here –>
<p>Please <a class=”show-popup” href=”#” data-showpopup=”1″ >click here</a> to see the popup 1</p>
<p>Try <a class=”show-popup” href=”#” data-showpopup=”2″ >clicking here</a> to see the popup 2</p>
<p>Now try <a class=”show-popup” href=”#” data-showpopup=”3″ >clicking here</a> to see the popup 3</p>
</div>

<div class=”overlay-bg”>
</div>
<div class=”overlay-content popup1″>
<p>Oh My! This is a popup!</p>
<button class=”close-btn”>Close</button>
</div>
<div class=”overlay-content popup2″>
<p>This is the content for Popup #2</p>
<button class=”close-btn”>Close</button>
</div>
<div class=”overlay-content popup3″>
<p>This is the content for Popup #3</p>
<button class=”close-btn”>Close</button>
</div>

</body>
</html>
[/HTML]

You’ll notice that I added data-showpopup="" to the anchor tags. We will use this to show which popup we want to show depending on the class name added to the overlay-content divs.

CSS Snippet

And below is the CSS we’ll be using to style our popup overlay:

[CSS]
* {
margin: 0;
padding: 0;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}

body {
font-family: ‘Helvetica Neue’,’Helvetica’, Arial, sans-serif;
}

.main-content {
height: 800px;
width: 1000px;
margin: 0 auto;
}

.overlay-bg {
display: none;
position: absolute;
top: 0;
left: 0;
height:100%;
width: 100%;
cursor: pointer;
z-index: 1000; /* high z-index */
background: #000; /* fallback */
background: rgba(0,0,0,0.75);
}
.overlay-content {
display: none;
background: #fff;
padding: 1%;
width: 40%;
position: absolute;
top: 15%;
left: 50%;
margin: 0 0 0 -20%; /* add negative left margin for half the width to center the div */
cursor: default;
z-index: 10001;
border-radius: 4px;
box-shadow: 0 0 5px rgba(0,0,0,0.9);
}

.close-btn {
cursor: pointer;
border: 1px solid #333;
padding: 2% 5%;
background: #a9e7f9; /* fallback */
background: -moz-linear-gradient(top, #a9e7f9 0%, #77d3ef 4%, #05abe0 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#a9e7f9), color-stop(4%,#77d3ef), color-stop(100%,#05abe0));
background: -webkit-linear-gradient(top, #a9e7f9 0%,#77d3ef 4%,#05abe0 100%);
background: -o-linear-gradient(top, #a9e7f9 0%,#77d3ef 4%,#05abe0 100%);
background: -ms-linear-gradient(top, #a9e7f9 0%,#77d3ef 4%,#05abe0 100%);
background: linear-gradient(to bottom, #a9e7f9 0%,#77d3ef 4%,#05abe0 100%);
border-radius: 4px;
box-shadow: 0 0 4px rgba(0,0,0,0.3);
}
.close-btn:hover {
background: #05abe0;
}

/* media query for most mobile devices */
@media only screen and (min-width: 0px) and (max-width: 480px){

.overlay-content {
width: 96%;
margin: 0 2%;
left: 0;
}
}

[/CSS]

jQuery Snippet

And here’s the jQuery snippet we’ll use to trigger the popup to display (Note: I’m using jQuery version 1.9):

[JAVASCRIPT]
$(document).ready(function(){

// function to show our popups
function showPopup(whichpopup){
var docHeight = $(document).height(); //grab the height of the page
var scrollTop = $(window).scrollTop(); //grab the px value from the top of the page to where you’re scrolling
$(‘.overlay-bg’).show().css({‘height’ : docHeight}); //display your popup background and set height to the page height
$(‘.popup’+whichpopup).show().css({‘top’: scrollTop+20+’px’}); //show the appropriate popup and set the content 20px from the window top
}

// function to close our popups
function closePopup(){
$(‘.overlay-bg, .overlay-content’).hide(); //hide the overlay
}

// timer if we want to show a popup after a few seconds.
//get rid of this if you don’t want a popup to show up automatically
setTimeout(function() {
// Show popup3 after 2 seconds
showPopup(3);
}, 2000);

// show popup when you click on the link
$(‘.show-popup’).click(function(event){
event.preventDefault(); // disable normal link function so that it doesn’t refresh the page
var selectedPopup = $(this).data(‘showpopup’); //get the corresponding popup to show

showPopup(selectedPopup); //we’ll pass in the popup number to our showPopup() function to show which popup we want
});

// hide popup when user clicks on close button or if user clicks anywhere outside the container
$(‘.close-btn, .overlay-bg’).click(function(){
closePopup();
});

// hide the popup when user presses the esc key
$(document).keyup(function(e) {
if (e.keyCode == 27) { // if user presses esc key
closePopup();
}
});
});
[/JAVASCRIPT]

Download Source File

Source File: how-to-create-overlay-popup.zip

Conclusion

That’s it! Try it out for yourself, or create your own version of a popup overlay.

If you would like to see more of these tutorials, or maybe you have a suggestion for me, let me know in the comments below.

Update (03/25/2014)

There have been some concerns about functionality in mobile browsers when dealing with this popup overlay. I have updated the jQuery code and CSS to fix the issue.

Update (07/14/2014)

A lot of people have been asking how to show a different popup when they click on a link. I’ve updated the code and tutorial to allow you to show different content for the popup using a data binding and adding a class name to the overlay-content divs.

Update (11/3/2014)

Special thanks to Janos for figuring out a better solution to the popup overlay. I’ve adjusted the HTML, CSS, and JS to change the function of the popup overlay. Now all form inputs and links should work normally inside the popup overlay.

Update (12/1/2014)

Shout out to Matt Solomon for requesting a way for a user to press on the esc key to close the overlay. I’ve adjusted the JavaScript code to include that function.

Update (2/27/2015)

Shout out to HighOne for requesting a way to load the popup when a user first enters the page. I’ve updated the JavaScript code to include those new functions.

136 thoughts on “How to Create an Overlay Popup Box Using HTML, CSS, and jQuery

  1. Reallly good tutorial and really easy to follow. Thanks! I’ll definitely use this on my next website.

        • You can add this inside your script:

              $(document).keyup(function(e) {
                  if (e.keyCode == 27) { // if user presses esc key
                      $('.overlay-bg, .overlay-content').hide(); //hide the overlay
                  }
              });
          

          I’ll update the codebase to include this as well.

          • Thanks Alfonse, that worked great!
            Another question for you:
            I made my overlay with a scrolling overflow y. If I open it and scroll half the way down and then close it, when I reopen it, the scroll is still in the same spot. Is there a way to have the overlay refresh itself, or start from its top each time you click on it without having to refresh the whole parent?
            Thanks for your help

    • In your jQuery file, just include this anywhere to the top:


      $('.overlay-bg').show();

      Or if you want to display the popup and fade it in after several seconds, you can do this instead:


      setTimeout(function() {
      $('.overlay-bg').fadeIn('slow'); // this will fade in the popup
      }, 2000); //show popup after 2000 milliseconds(2 secs)

      • can you show me how, when you go to the website in a matter of seconds a pop up box with close button will show up

      • I think you may have modified the JQuery file since suggesting the auto-popup addition, as I cannot get this to work now. What can be added/changed to now make the popup happen on page load? I tried changing the event to “load”, but I guess it’s not that simple. I’m certainly not a JQuery guy! Thanks in advance – great code!

  2. Great Information. I really appreciate it. looked for it for long time …

    Now I’m trying to have a picture in the pop up window and my picture size is 800×600. it covers the Close button and goes outside the popup window. what should I do for that ?

    • There are several ways to do that depending on your html. A simple fix would be to add this your CSS:


      .overlay-content img {
      max-width: 100%;
      }

      That should constrain your image within the popup box container.

      If you want to expand or widen the popup container to better fit larger images, you can also play around with the CSS values of the “.overlay-content” selector like so:


      .overlay-content {
      background: #fff;
      padding: 1%;
      width: 80%;
      position: relative;
      top: 5%;
      left: 10%;
      margin: 0;
      border-radius: 4px;
      box-shadow: 0 0 5px rgba(0,0,0,0.9);
      }

      All I did was updated the width, left, and margin properties. Try it and see if that works for you.

    • What do you mean onload event? Do you mean the on $(document).ready() event?

      The script I wrote uses jQuery to load events such as $(‘.show-popup’).click() function after the DOM has been loaded. Also, the $(document).ready() function is jQuery specific.

  3. I am trying to use your overlay tutorial to create a popup iFrame for my shirt shop but I can’t seem to figure out what I’m doing wrong. I’ve edited the pop up a little bit to ‘fit’ my iframe but now, when creating multiple instances of the overlay, it always shows the same iframe, even whilst being linked separately.

    Example is on my home page at http://wearourdesigns.com

    Do you have any idea what Im doing wrong? Thanks.

    • I looked at your HTML structure and came up with this jQuery snippet just for your site. Just Replace the old $(‘.show-popup’).click() function with this new one:


      $('.show-popup').click(function(event){
      event.preventDefault();
      $(this).closest('.columns').find('.overlay-bg').show();
      });

      What I did was to traverse up your HTML structure by using the .closest() function and targeting the ‘.columns’ container and then finding the correct ‘.overlay-bg’ to show.

  4. Hi, great tutorial. Is it possible to add many “click here” buttons to open different pop ups in the same page, and these pops with different contents? Thanks a lot.

    • The best way to do that is to make the content inside the ‘.overlay-content’ div to be dynamic so that you don’t have to create multiple ones for each ‘click here’ button. Here’s an example of how to achieve this:

      First let’s start by adding an extra class to the link to differentiate which popup content should show – in this case we’ll add a class of ‘popup1’ and ‘popup2’ like so.

      HTML:

      <p><a href="#" class="show-popup popup1" rel="nofollow">Click Here for popup 1</a></p>
      <p><a href="#" class="show-popup popup2" rel="nofollow">Click Here for popup 2</a></p>

      Now we’ll do a check to see which popup content we want to show.

      JavaScript:

      $(document).ready(function(){
      // show popup when you click on the link
      $('.show-popup').click(function(event){
      event.preventDefault(); // disable normal link function so that it doesn't refresh the page

      if($(this).hasClass('popup1')){
      $('overlay-content').html('<p>This is the new content for popup 1</p>');
      }
      if($(this).hasClass('popup2')){
      $('overlay-content').html('<p>This is the new content for popup 2</p>');
      }
      $('overlay-content').append('<button class="close-btn">Close</button>'); //don't forget to add the close button
      $('.overlay-bg').show(); //display your popup
      });

      // hide popup when user clicks on close button
      $('.close-btn').click(function(){
      $('.overlay-bg').hide(); // hide the overlay
      });
      });

      Mind you, that’s just a very simple and basic way of changing the content inside the overlay-content div. There are other ways that you can do to make the content much more dynamic and robust depending on what you want it to do.

      • Thanks for your help. The code almost work, except when it calls a different “#” for the href.. The Click Here link… always display the same pop up window. Do you have any idea why? thanks.

  5. This is very informative however, I’m trying to make my Mailchimp Subscribe Form a popup overlay. I can’t seem to figure out where I am to embed the code in the html or css. Can you help?

    • You can add the Subscribe form inside the .overlay-content div.

      As for embedding the code, you just need to add the javascript and css inside your head tags by pointing to it. I have it set up like so:


      <script type="text/javascript" src="custom.js"></script>
      <link href='overlaypopup.css' rel='stylesheet' type='text/css'/>

      Then you just need to add a class of ‘show-popup’ to any element in your html (preferably an achor tag) that you want people to click on and show the Subscribe form.

      Let me know if that helps.

      • “Then you just need to add a class of ‘show-popup’ to any element in your html (preferably an achor tag) that you want people to click on and show the Subscribe form.”

        What does this mean exactly?

    • The easiest way to allow that is to add a ‘height’ property with a value and ‘overflow: scroll;’ to the ‘.overlay-content’ selector in your CSS like so:


      .overlay-content {
      height: 200px; /* or whatever height you want to set */
      overflow: scroll;
      }

      That way, if the content is longer than 200px height, it will create a scroll bar inside the popup for the user to scroll in.

  6. Thanks very much for your tutorial. But how do you tweak it so that the popup overlay goes away when the user clicks anywhere outside the overlay container? Also, the overlay will remain if the user clicks anywhere inside the overlay but only closed when the close button is pressed.

    • So in order to do this we must add two things in our jQuery script:
      —————————————-

      $('.overlay-content').click(function(){
      return false;
      });
      $('.overlay-bg').click(function(){
      $('.overlay-bg').hide();
      })


      —————————————-
      So the first one checks to see if you’ve clicked inside the overlay container. If you do click inside it, it will just return false and won’t do anything.

      The next one checks to see if you’ve clicked pretty much anywhere when the popup overlay is shown, including the overlay container itself. However, since we added the first script, it will cancel this script if the user clicks inside the overlay container.

      For added effect you can also add this to your CSS:
      —————————————-

      .overlay-bg {
      cursor: pointer;
      }

      .overlay-content {
      cursor: default;
      }


      —————————————-
      Hope that helps.

      ALSO: I’ve updated the article and files to include this functionality. Thank you for your input!

  7. Hey Alfonse,

    Great work btw, I really love this pop-up, especially having searched the internet for quite a few hours now. That being said, I was wondering where exactly to input the code to fadein/fadeout?

    I know you mentioned how to do so above, but I don’t know where to place it within the jquery text, and when I try, the pop-up doesn’t appear when I click on it.

    If there’s anyway you can help me insert:

    setTimeout(function() {
    $(‘.overlay-bg’).fadeIn(‘slow’); // this will fade in the popup
    }, 2000); //show popup after 2000 milliseconds(2 secs)

    I’d really appreciate it :)

    • Hey John,

      The script above works if you add it somewhere between your $(document).ready() function. However, I think the issue may have been that if you copy and pasted the code from the comments, it may have copied some illegal characters in place of the apostrophes (‘). I’ve fixed my comments so you are able to copy and paste the code correctly.

      I’ve added the code as an example below:


      $(document).ready(function(){

      setTimeout(function() {
      $('.overlay-bg').fadeIn('slow'); // this will fade in the popup
      }, 2000); //show popup after 2000 milliseconds(2 secs)

      // show popup when you click on the link
      $('.show-popup').click(function(event){
      event.preventDefault(); // disable normal link function so that it doesn't refresh the page
      $('.overlay-bg').show(); //display your popup
      });

      // hide popup when user clicks on close button
      $('.close-btn').click(function(){
      $('.overlay-bg').hide(); // hide the overlay
      });

      // hides the popup if user clicks anywhere outside the container
      $('.overlay-bg').click(function(){
      $('.overlay-bg').hide();
      })

      // prevents the overlay from closing if user clicks inside the popup overlay
      $('.overlay-content').click(function(){
      return false;
      });

      });

  8. Hey Alfonse!

    Thanks so much for getting back to me :) I really appreciate it.

    I’ve included the above code, however, when I click on the button the box immediately pops up. After I click outside the box to make it disappear, the box suddenly fades into existence.

    I’d also like to know if it’s possible to repeat this fadein function so that if a user clicks on it a second time, maybe they changed their mind, it will repeat the same effect. Is this possible?

    Here is an example of what I’m trying to accomplish here:
    http://www.cantedpictures.com/3test/

    • Hey John,

      It’s simple really. I just added a variable that checks if the popup has popped already and determine if I should show the popup again or not. I’ve also added more fade in/out effects as well. Here’s an updated script for you to use. I’ve included comments so you get an idea of what it’s doing.


      $(document).ready(function(){

      var popped = false; // used to check if popup has opened

      setTimeout(function() {
      if(!popped){ //if popped is false then show popup
      $('.overlay-bg').fadeIn('slow'); // this will fade in the popup
      }
      }, 2000); //show popup after 2000 milliseconds(2 secs)

      // show popup when you click on the link
      $('.show-popup').click(function(event){
      event.preventDefault(); // disable normal link function so that it doesn't refresh the page
      $('.overlay-bg').fadeIn('slow'); //display your popup
      popped = true; // set popped to true
      });

      // hide popup when user clicks on close button
      $('.close-btn').click(function(){
      $('.overlay-bg').fadeOut('fast'); // hide the overlay
      });

      // hides the popup if user clicks anywhere outside the container
      $('.overlay-bg').click(function(){
      $('.overlay-bg').fadeOut('fast');
      })

      // prevents the overlay from closing if user clicks inside the popup overlay
      $('.overlay-content').click(function(){
      return false;
      });

      });

      • Hey Alfonse!

        That worked PERFECTLY. Man I love this code. Already bookmarked your site and will definitely encourage others to check this out. Very happy with your quick responses and how informative you are. Thank you again :)

        I’m able to tweak everything else independently, but there’s two more things I was curious about:

        1. How can I change the text color of the “Close” button from black to white?

        2. And also, how can I control the opacity in the background?

        Thanks again for everything. I’ve honestly spent two solid days searching for a decent overlay pop-up and this was by far the best.

        Take care,
        John

        • Thanks John! I really appreciate that. I’m just glad the script helped you out.

          As for changing the color of the button from black to white, you just need to add the color property into your CSS within the .close-btn selector like so:


          .close-btn {
          color: #fff; /* white */
          }

          And as for changing the opacity value of the background, you can also edit the background: rgba() value inside the .overlay-bg selector like so:


          .overlay-bg {
          background: rgba(0,0,0,0.75); /* change 0.75 to any number between 0 and 1. For example: 0.5 or 0.2 */
          }

          Hopefully that helps.

  9. Hey Alfonse,

    That was great, worked perfectly as always. Didn’t realize it was that simple lol.

    Truly one last question: I noticed that if I shrink the browser, the pop-up box shrinks as well; is there a way of changing it so the box stays at a fixed height/width? I know some people like their browser windows tiny, others much larger; however, I wanted a consistent experience across the board.

    Aside form that, I’ve gotten your code to perfectly match what I (and my company) had wanted :)

    • This is also another easy thing to do. All you need to do is edit the CSS within the .overlay-content selector like so:


      .overlay-content {
      width: 600px; /* set to whatever size width you want */
      margin: 0 0 0 -300px; /* make sure the last value is negative half of the width */
      }

  10. I have to say, this is fantastic! Thank you again, Alfonse.

    Anyone interested in adding an overlay pop-up will benefit from this code – clean, simple to use, and versatile.

    Great work!

  11. Excellent work on the overlay code – been looking one for a long, long time. I’ve recently implemented your code to display videos, but when a user clicks “close-btn” or clicks outside the overlay, the youtube video continues to play in the background.

    Is there a way to change this so when a user clicks outside the box, the video stops playing altogether?

  12. hello, nice work!! just a doubt. I just use an email address in that popup (<a href="mailto:….), but I cant get it work. It´s not popping up my email program to write a mail..just happen nothing.
    Thanks in advance…

    • The reason it’s not working is because of the event.preventDefault(); inside jQuery script that shows the popup overlay as shown below:

      $('.show-popup').click(function(event){
              event.preventDefault(); // disable normal link function so that it doesn't refresh the page
              $('.overlay-bg').show(); //display your popup
          });
      

      if you want it to open an email, just comment out that line or delete it and the email functionality should work again.

      • Hi Alfonse, tried this before already, Links or emails don´t work even if I put them in the simple download example.thanks for help

      • I’m having the same issue. Links don’t work within the overlay. Any ideas? I’ve removed the event.preventDefault(); function.

  13. Hey Alfonse,

    Tried implementing the code using your link as an example, but I wasn’t able to get it to work. Here is the complete code for java, css, and HTML:

    http://jsfiddle.net/Hwilhelm/MPb7G/3/

    When I click “close-btn” the video continues playing in the background while clicking outside the overlay results in a repeat function. I was going to use return false to cancel this, but just wanted to make sure that was the right code to use.

    Thanks again

  14. Hi there,
    thanks a lot for this splendid tutorial.
    I’d like to ask you one thing: it is possible to open an external url in the popup?
    So that I can put a contact form or a google maps loaded from a file?

    Thanks in advance!!
    Marco

    • There’s many ways you can do this but the easiest would probably be to include an iframe inside the .overlay-content div. for example:

      <div class="overlay-bg">
      	<div class="overlay-content">
      		<iframe src="http://www.hallofhavoc.com"></iframe>
      		<button class="close-btn">Close</button>
      	</div>
      </div>
      

      Then you could also style the iframe within your css to fit your popup overlay like so:

      iframe {
      	width: 100%;
      	height: 50%;
      }
      
  15. Hey Alfonse,

    Thanks for the YouTube API: I’ve actually spent the last few days playing with the chromeless player and so forth.

    I was also curious if you know about the elastic transition for javascript? this is not a big deal, but instead of using the fadein transition, i was hoping to implement the autosize elastic as seen here:

    http://www.imdb.com/trailers/

    (If you click on any trailer, the overlay will autosize to the specified dimensions and kind of jump out)

    • You can do something similar like the code below. It uses CSS3 transitions for newer browsers but will still default to the specified width for browsers that don’t support CSS3 transitions.

      Here’s the sample jQuery code. I rewrote the jQuery slightly.

      $(document).ready(function(){
          // show popup when you click on the link
          $('.show-popup').click(function(event){
              event.preventDefault(); // disable normal link function so that it doesn't refresh the page
              $('.overlay-bg').fadeIn('fast').addClass('open'); //display your popup
          });
      
          // hide popup when user clicks on close button
          $('.close-btn').click(function(){
          	closePopup(); // hide the overlay
          });
      
          // hides the popup if user clicks anywhere outside the container
          $('.overlay-bg').click(function(){
          	closePopup(); // hide the overlay
          })
          // prevents the overlay from closing if user clicks inside the popup overlay
          $('.overlay-content').click(function(){
      		return false;
      	});
      });
      
      function closePopup(){
          $('.overlay-bg').fadeOut('fast').removeClass('open');
      }
      

      You’ll notice that I just added a class to the overlay-bg div and removed it when closing the popup overlay.

      And here’s the new CSS to support the transition animation:

      * {
      	margin: 0;
      	padding: 0;
      	-moz-box-sizing: border-box; 
      	-webkit-box-sizing: border-box; 
      	box-sizing: border-box;
      }
      
      body {
      	font-family: 'Helvetica Neue','Helvetica', Arial, sans-serif;
      }
      
      .main-content {
      	height: 800px;
      	width: 1000px;
      	margin: 0 auto;
      }
      
      .overlay-bg {
      	display: none;
      	position: fixed;
      	top: 0;
      	left: 0;
      	height:100%;
      	width: 100%;
      	cursor: pointer;
      	background: #000; /* fallback */
      	background: rgba(0,0,0,0.75);
      }
      	.overlay-content {
      		background: #fff;
      		padding: 1%;
      		width: 40%;
      		position: relative;
      		top: 15%;
      		left: 50%;
      		margin: 0 0 0 -20%; /* add negative left margin for half the width to center the div */
      		cursor: default;
      		border-radius: 4px;
      		box-shadow: 0 0 5px rgba(0,0,0,0.9);
      		-webkit-transition: all .5s ease;
      		   -moz-transition: all .5s ease;
      		    -ms-transition: all .5s ease;
      		     -o-transition: all .5s ease;
      		        transition: all .5s ease;
      	}
      	.overlay-bg.open .overlay-content {
      		width: 80%; /* changed the width when overlay-bg has a class of 'open' */
      		margin: 0 0 0 -40%; /* used to center the overlay-content */
      	}
      
      	.close-btn {
      		cursor: pointer;
      		border: 1px solid #333;
      		padding: 2% 5%;
      		background: #a9e7f9; /* fallback */
      		background: -moz-linear-gradient(top,  #a9e7f9 0%, #77d3ef 4%, #05abe0 100%);
      		background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#a9e7f9), color-stop(4%,#77d3ef), color-stop(100%,#05abe0));
      		background: -webkit-linear-gradient(top,  #a9e7f9 0%,#77d3ef 4%,#05abe0 100%);
      		background: -o-linear-gradient(top,  #a9e7f9 0%,#77d3ef 4%,#05abe0 100%);
      		background: -ms-linear-gradient(top,  #a9e7f9 0%,#77d3ef 4%,#05abe0 100%);
      		background: linear-gradient(to bottom,  #a9e7f9 0%,#77d3ef 4%,#05abe0 100%);
      		border-radius: 4px;
      		box-shadow: 0 0 4px rgba(0,0,0,0.3);
      	}
      	.close-btn:hover {
              background: #05abe0;
          }
      
      

      Here you’ll notice that all I did was to add a transition to the .overlay-content selector and then created a selector called .overlay-bg.open .overlay-content which changes the width and margin. Let me know if that helped you out.

      Also, here’s a JSFiddle for the demo: http://jsfiddle.net/JPRaV/

      • Hey Alfonse,

        I honestly tried several times, and didn’t want to respond until I figured it out, but unfortunately I couldn’t get it to work. Sometimes the iframe wouldn’t scale, other times it scaled from the left, and so on.

        Here is the exact code I am currently using: http://jsfiddle.net/Hwilhelm/MPb7G/34/

        It also includes the video player ID to stop the youtube player if clicked outside the box, as well as other codes you’ve written. I’m not sure if you’re able to add the new transition animation to the above demo – if it’s too much trouble, don’t worry about it :)

        • Hey Alfonse,

          I realize what the problem was: the overlay-content would autosize and scale while the YouTube Embed remained the same.

          I took another look at the IMDb trailers and they waited for the overlay to autosize until the width/height were the appropriate dimensions, and then the video loaded.

          Should I use the Settimeout function or delay function? If so, how would I target the video specifically? This would solve the problem as the code is fine – it’s the embed that’s screwing things up.

          • Hey I just looked at the JSFiddle you had posted earlier and noticed a few things missing from the code. The html had missing closing divs, the css had an extra closing bracket and didn’t have the transition applied, and the jQuery script was missing the .addClass() and .removeClass() functions to make the transition work.

            Anyways, I fixed all the issues and updated the JSFiddle here: http://jsfiddle.net/MPb7G/40/

  16. thanks for the code, its great!

    i was wondering why it seems to over ride html coding. Basically i have multiple paragraphs in the pop but there is no spacing between the them. Any thoughts why its over riding the coding?

    thanks

    • It’s probably because of the CSS reset for margin and padding. In the CSS you’ll notice that I put

      * {
      	margin: 0;
      	padding: 0;
      	-moz-box-sizing: border-box; 
      	-webkit-box-sizing: border-box; 
      	box-sizing: border-box;
      }
      

      You can get rid of that part if you want to keep the browser defaults.

  17. Hey Alfonse,

    Thanks for the great, easy to implement popup overlay. It works like a charm!

    Is it possible to turn off the scroll function for the main page if the popup is opened?

    I’m using the scroll function in the popup itself and when I scroll all the way down to the end of the content of the popup the popup content stops scrolling (obviously;-), but then if I scroll a bit more the main page scrolls to a different position.

    Thanks again for your great work!

    Cheers,

    Ran

    • The easiest way to prevent the whole page to scroll while still allowing you to scroll within the popup is to prevent scrolling on the ‘body’ element.

      You can update your jQuery click function like this:

      $('.show-popup').click(function(event){
          event.preventDefault(); // disable normal link function so that it doesn't refresh the page
          $('.overlay-bg').fadeIn('fast').addClass('open'); //display your popup
          $('body').css({'overflow':'hidden'}); //this will prevent the entire page to scroll
      });
      

      You’ll notice that I added the extra css to the body element when the popup shows up. This will prevent the whole page to scroll.

      Then in the closePopup() function, you’ll want to remove that overflow: hidden; css from the body like so:

      function closePopup(){
          $('.overlay-bg').fadeOut('fast').removeClass('open');
          $('body').css({'overflow':'auto'}); //allow you to scroll the page again
      }
      

      That’s it. Hope that helps.

  18. Super cool coding brother!

    Check this one out…

    I got it to work (still working on the subscribe button) but the popup window gets stuck behind the slider.

    What would you say to adjust this one?

  19. Hello,

    Your code is simply superb but need to tweak the code as per my questions.

    How do we show pop up with different images by clicking on multiple thumb images/links?
    I have seen one comment above, same kind of requirement where you have added multiple lines of code in JS but is there any other way to do more robust as there would be n number of links/thumbs along with large images.
    How do we show other large images in pop up by clicking prev and next buttons?
    Is there a way to set up pagination in main page, question kind of not relevant to pop up?

    • Hi Pattabhi,

      that’s actually a great question. Unfortunately this tutorial is used to display a basic popup overlay.

      However, you have given me a great idea to create a tutorial on how to create an image gallery popup which I will post up very soon.

  20. These windows are a great way to break basic browser functionality (forward/back and linking) and completely destroy all usability on mobile browsers.

    • Hi Abscissa, thanks for the concern.

      I have updated the code and fixed the mobile functionality issue. Mobile(and desktop for that matter) are now able to scroll without being fixed to the window screen.

      As for breaking basic browser functionality, I’m not quite sure what you mean but this only affects anchor tags with a class name of ‘show-popup’ and won’t affect any other browser functionality.

      If you can elaborate, please let me know and I would gladly update the code to fix the issue.

      • Nice.

        Although I admit I haven’t tried your specific implementation, I have yet to come across an overlay window in the wild that works properly with back/forward buttons and linking/bookmarking.

  21. If I have already created an ad block detector, how can I created a press+(like) semitransparent overlay window that would pop up when an ad is detected?

    • Hi Charlie,

      It’s a bit difficult to figure this out unless I knew the code for the ad block detector. My best guess would be to just show the popup when you detect an ad.

      If, for example, you’re using my popup overlay code, you can do something like this:

      adDetected = function(){
      	var docHeight = $(document).height();
      	$('.overlay-bg').show().css({'height' : docHeight});
      }
      

      and in your ad block detector code, once it detects an ad that was blocked, you can just call the adDetected() function.

      Like I said, this is just in theory since I don’t know your code for your ad block detector, but hopefully this should push you in the right direction.

      • Where would I add the code below to your popup overlay code?

        adDetected = function(){
        var docHeight = $(document).height();
        $(‘.overlay-bg’).show().css({‘height’ : docHeight});
        }

        • Maybe I misunderstood your initial question, but that function is to be called in your ad block detector code.

          Maybe you can elaborate as to what exactly you’re trying to do with the popup.

          • This is my adblock detector code:

            Adblock Detector

            function _status(isDetected) {
            alert(‘detected: ‘+isDetected);
            }
            var _abdStatusFnc = ‘_status’;

            adDetected = function(){
            var docHeight = $(document).height();
            $(‘.overlay-bg’).show().css({‘height’ : docHeight});
            }

            I’m trying to figure out how to: if an ad is detected, to have a (press+ like) semitransparent overlay window to pop up

          • Sorry, here is the original version:

            Adblock Detector

            function _status(isDetected) {
            alert(‘detected: ‘+isDetected);
            }
            var _abdStatusFnc = ‘_status’;

  22. I have the popup content in another html page how do i invoke this using this code snippet.

    I was tried to include the html page in the anchor href to no avail.

    any help is greatly appreciated.

    • Hi masticrv,

      This is actually pretty easy to do. Since you’re adding the url of the page you want to load into the href value of the anchor tag, then you can just do this:

      // show popup when you click on the link
          $('.show-popup').click(function(event){
              event.preventDefault(); // disable normal link function so that it doesn't refresh the page
              var docHeight = $(document).height(); //grab the height of the page
              var scrollTop = $(window).scrollTop(); //grab the px value from the top of the page to where you're scrolling
              var pageurl = $(this).attr('href'); //grab the href value from the anchor tag
              $('.overlay-bg').show().css({'height' : docHeight}); //display your popup and set height to the page height
              $('.overlay-content').css({'top': scrollTop+20+'px'}); //set the content 20px from the window top
              $('.overlay-content').load(pageurl); //load the page from the url
          });
      

      You’ll notice that I added two things. A variable called pageurl that grabs the href value in the anchor tag. And then I’m loading the content directly into the $('.overlay-content') div.

      Hope that helps.

  23. Hello Alfonse,

    This has been incredibly helpful. I’m running into a problem though. I have a page, which I would like to use this several times on. I used it once, created a second one, but now the video isn’t popping up in front of the overlay for whatever reason?

    Here is the link: http://takecontroldelaware.com/stories.html

    The woman, she pops up great, but then when you go over to the guy, you can hear him but not see him? I’m sure this is a simple fix… but I’m not sure what it is.

  24. Hi, and thanks for your work. Is thete a way to show popup only one/visitor? I load the script in a header template wich loads on every page. I want to display popup just once.

    Thank you.

    • I think what you need to do is have a seperate style for that section. You can still use the general style but just add some style for that page only. Do this by adding a tag in the tag. Same code as if you were writing in css. Hope I helped and it’s not too late a reply.

  25. hey this was very useful for me. but i’m experiencing a little problem. i have put an upload form in the pop up but when i want to choose the file nothing happens. i can click over it but there is no response, i guess u have currently made the pop up for only displaying information purpose, and not for any function. any help would be appreciated.

    Change Profile Picture

    Close

  26. Hi, I am new for web application. Really it is awesome one and I never find this kind of simple solutions. I have some query.
    1. In my webpage I have 10 view more details link and while clicking each link I want to show the overlay-popup window with (different details) detials based on the click. Please help me. I need the full code.
    2. Where I need to add the below code for avoiding the page scroll?
    function closePopup(){
    $(‘.overlay-bg’).fadeOut(‘fast’).removeClass(‘open’);
    $(‘body’).css({‘overflow’:’auto’}); //allow you to scroll the page again
    }

    Please help me or send me the entire script to my mail ID.
    Thanks.

  27. Hi Alfonse,
    Thanks a lot.This is very useful for me.

    I would like to know how to move the popup overlay to middle of the page with animated effect, when scrolling the page,

  28. working fine with the below code

    $(window).scroll(function(){
    $(‘.overlay-content’).stop();
    $(‘.overlay-content’).animate({“marginTop”: ($(window).scrollTop() + 30) + “px”}, “slow” );
    });

  29. I have multiple popups which are activated by clicking on expand. I can’t click on them individually, if I do it opens up the one I added first with the other ones behind it. Any ways to fix this?

  30. Hi, great tutorial. Is it possible to add many “click here” buttons to open different pop ups in the same page, and these pops with different contents? Thanks a lot

  31. A lot of people have been asking about how to show different popups on the page that contains different content. I’ve updated the code to reflect that. Now all you have to do is add data-showpopup="1" to your anchor tags and add the classname of popup1 to the corresponding <div class="overlay-content" >...</div> you want to show.

  32. Thank you for this great popup code.

    One question. Is it possible to just have the popup display one time, so that returning visitors do not see it multiple times?

  33. Hi Alfonse,
    Thanks for the great code, the only problem I am having is that links don’t work inside the popup. I have deleted the event.preventDefault(); line but they still don’t work.

    If I right click on the link then I can open it in a new tab or window, but when just clicking on it nothing happens. I have tried all the various ‘target’ options.

    Thanks for your help,
    George

    • Problem solved! Funny how just typing that question caused me to look more closely at the rest of the code. I removed the
      $('.overlay-content').click(function(){
      return false;
      });
      section as well. This does mean clicking inside the popup now closes it, but at least the link works!

      Is there any way of just allowing links to work, but a click anywhere else inside the popup does nothing?

      Thanks,
      George

      • Hi George,
        good catch! One solution would be to just comment out the $('.overlay-bg').click(function(){...}) and the $('.overlay-content').click(function(){...}) sections and just have users click on the close button instead to close the popup overlay.

    • You’ll notice on the previous comment that adding the return false; inside of the $('.overlay-content').click() function was causing issues with form inputs.

      You can just comment out the $('.overlay-bg').click() and $('.overlay-content').click() functions like so:

      $(document).ready(function(){
          // show popup when you click on the link
          $('.show-popup').click(function(event){
              // event.preventDefault(); // disable normal link function so that it doesn't refresh the page
              var docHeight = $(document).height(); //grab the height of the page
              var scrollTop = $(window).scrollTop(); //grab the px value from the top of the page to where you're scrolling
              $('.overlay-bg').show().css({'height' : docHeight}); //display your popup and set height to the page height
              $('.overlay-content').css({'top': scrollTop+20+'px'}); //set the content 20px from the window top
          });
       
          // hide popup when user clicks on close button
          $('.close-btn').click(function(){
              $('.overlay-bg').hide(); // hide the overlay
          });
       
          // hides the popup if user clicks anywhere outside the container
          // $('.overlay-bg').click(function(){
          //     $('.overlay-bg').hide();
          // })
          // // prevents the overlay from closing if user clicks inside the popup overlay
          // $('.overlay-content').click(function(){
          //     // return false;
          // });
       
      });
      
  34. I have something like

    Download

    popup is css div which opens popup windows when clicked on download, i also want that file should get downloaded and display pop up, now only popup displays and files does not get downloaded

  35. Words can’t describe how happy I am to use your code! After spending lots of time, days actually, reading other codes and trying other demos and having lots of issues for my simple portfolio needs, finding your demo has been a bless. Had read all the comments and they helped too. Amazing website, man!
    Thank you thank you thank you!

  36. Hi,

    instead of having the js code to prevent clicks on the .overlay-content to close the popup, you could also do this:
    1. add “z-index: 1001;” in the css of .overlay-content
    2. change “position:relative;” to “position:absolute;” in the css of .overlay-content
    3. change html to this:

    Oh My! This is a popup!
    Close

    This way normal links will still work inside the .overlay-content element, as it is no longer a child element of .overlay-bg :)

  37. How do I load the .html file, when I click on div to show that whole .html page inside the overlay. If any one have any Idea. Please post it. Thanks.

  38. Hi, I’m trying to make the pop-up to loaded when a person opens the website on first time, what should I do to make it?

    • Depending on your PHP templating, you can place this inside a PHP file that get’s loaded on every page (example: footer.php). Just make sure that you place the HTML code somewhere at the top level of your entire HTML structure.

  39. Greetings!

    I came upon your page while searching for this post’s sort of instructions. I operate my own blog and I was wanting to promote an NGO I work for on my blog via a pop-up when a user first visits my website.

    I just had two inquiries:

    1. Will the pop-up show up on every page? Or can it just show up on the landing page and then stay hidden for the rest of a user’s visit? (Perhaps maybe a ‘don’t show again’ option?)

    2. I have a very basic/elementary understanding of web design. I understand where to put the HTML and CSS, but where do I put the jQuery code?

    Thanks,

    Nolan

  40. Hi Alfonso! Thanks for posting this tutorial, after series of google search i found what I’ve been looking for. I just have 1 problem though, I need to use it on multiple popups, I using it as read more to shorten the intro text. I need 6 popups but they are relying on the data of the first pop up. Any thoughts?

    Thanks and more power!!

  41. Hi there, i’d like to load the popup and display some content, relevant to the link that called the popup i.e. if the user clicks on product in a table, two parameters are passed into the popup – account code and product code and data is displayed e.g. a graph of customer sales of the selected product …

    Thanks

    Kieran

  42. Thanks a lot for the tutorial … i need to create a popup box in which a gallery of pics will open and if clicked on any img it will show more info for the product in the same popup box

  43. I love this but also hate it… I love everything but the fact that the popup box is not centered like I want it in the middle but idk how to do it :( Please tell me

Leave a Reply

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