Adding a popup to a website is a very common requirement when we design a website. In addition, some additional requests may include:
- The popup should be centered both horizontally and vertically.
- Using a fly-in effect.
- It should overlay the existing HTML page and all elements.
- Hide the if click detected anywhere outside of it.
In this post, we will follow a step-by-step walk-through to design a popup and meet the requirements above.
First, let’s start from placing a simple div that will center both horizontally and vertically.
Adding a div with id=popup in the body of the HTML code. Feel free to add some content in the div, of course.
1 |
<div id="popup"></div> |
Center the popup both horizontally and vertically
Using the CSS style below, we are first trying to center the popup.
1 2 3 4 5 6 7 8 9 10 11 12 |
#popup{ width: 280px; height: 180px; position: fixed; top: 50%; left: 50%; padding: 10px; margin-top: -100px; margin-left: -150px; z-index: 999; background-color: #aaa; } |
Now take a look at the box model of the div, just to make sure the div is centered.
You can adjust the width and height for your div based on the content in your pop up. background-color property is set for purpose of testing.
Add a fly-in effect on the popup
Next, we can work on a fly-in effect by designing a fly-in class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
.fly-in { -webkit-animation: flyin 0.4s linear; /* Safari 4+ */ -moz-animation: flyin 0.4s linear; /* Fx 5+ */ -o-animation: flyin 0.4s linear; /* Opera 12+ */ animation: flyin 0.4s linear; /* IE 10+, Fx 29+ */ } @keyframes flyin { 0% { transform: translateY(100%); } 100% { transform: translateY(0%); } } |
Add a Shadow Overlay
Sometimes you need your entire browser window with a black overlay in the background. So the popup in the front can draw more attention to the visitors.
We already added a fly-in class to the div to implement the fly-in effect. Now let’s create another class to do the show overlay.
1 2 3 4 5 |
.shadow { -webkit-box-shadow: 0px 0px 0px 9999px rgba(0, 0, 0, 0.5); -moz-box-shadow: 0px 0px 0px 9999px rgba(0, 0, 0, 0.5); box-shadow: 0px 0px 0px 9999px rgba(0, 0, 0, 0.5); } |
Hide the popup when the user clicks outside of it
You may put a ‘Close’ or ‘X’ button in your popup, which is pretty straightforward. So visitor can close it if they think it is disturbing.
In addition, to be more user-friendly, we want the popup to disappear from the screen when someone clicks anywhere outside the popup div. This is where javascript kicks in.
Put the javascript code below in the $( document ).ready() function.
Basically, it adds an event handler for mouseup event on the HTML page. and if what is being clicked is not the popup div or any descendant element of it, then hide the it.
1 2 3 4 5 6 7 8 9 10 |
$(document).mouseup(function(e) { var container = $("#popup"); if (!container.is(e.target) && container.has(e.target).length === 0) { container.hide(); } }); |