Alessandro Dotti Contra

Linux/Unix DevOps


JQuery pop-up

A pop-up is a convenient way to grab the user's attention and notify him something you deem as important.

HTML markup

<div id="overlay">
	<div id="pop-up">
		<h3>This is a pop-up with a generic message.</h3>
		<p>Click anywhere to return to the page.</p>
	</div>
</div>

Here we prepare an overlay, which will obscure the page and make room for our pop-up, and the pop-up itself.

CSS snippet

body {
	position: relative;
}

#overlay {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: rgba(0, 0, 0, 0.7);
}

#pop-up {
	position: relative;
	color: #000000;
	background: #ffffff;
	top: 50%;
	left: 50%;
	width: 350px;
	height: 100px;
	padding: 25px;
	text-align: center;
	transform: translateX(-50%) translateY(-50%);
}

The overlay will cover the whole page with a 30% transparent black layer, while the pop-up will be centered in the page.

Code snippet

<script type="text/javascript">

function openPopUp() {
	$('#overlay').fadeIn();
	$('#overlay').click(function(e) {
		e.preventDefault();
		closePopUp();
	});
}

function closePopUp() {
	$('#overlay').fadeOut();
}

$(document).ready(function() {
	$('#overlay').hide();
	openPopUp();
});

</script>

The logic here is pretty simple: the openPopUp() function fades-in the pop-up and binds the click event of the overlay, so we can fade-out the pop-up by clicking anywhere on the viewport. The pop-up will appear as soon as the page is loaded.

View demo