Simple jQuery Overlay
by Vignesh Gopalakrishnan
HTML
<div id="overlay-inAbox" class="overlay">
<div class="toolbar"><a class="close" href="#"><span>x</span> close</a></div>
<div class="wrapper">
Hello! I'm in a box.
</div>
</div>
<a href="#" id="overlaylaunch-inAbox">Launch It!</a>
CSS
/* Base and example */
body {
background-color: #ccc;
font-size: 88%;
line-height: 1.6;
font-family: Arial, Helvetica, sans-serif;
color: #4e4e4e;
padding: 0;
}
a#overlaylaunch-inAbox {
display: block;
padding: 40px;
margin: 40px;
background-color: #efefef;
font-size: 1.6em;
text-decoration: none;
text-align: center;
}
#overlay-inAbox .wrapper {
text-align: center;
}
/* More important stuff */
.overlay,
#overlay-shade {
display: none;
}
#overlay-shade {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 9999;
background-color: #000;
}
.overlay {
position: absolute;
top: -300px;
left: 0;
width: 450px;
min-height: 200px;
z-index: 10000;
background-color: #7D7D7D;
border: 10px solid #CFCFCF;
color: #fff;
box-shadow: 0 0 16px #000;
} .ie7 .overlay {
height: 200px;
} .overlay .wrapper {
padding: 15px 30px 30px;
}
.overlay .toolbar {
padding: 8px;
line-height: 1;
text-align: right;
overflow: hidden;
} .overlay .toolbar a.close {
display: inline-block;
*display: inline;
zoom: 1;
padding: 0 8px;
font-size: 12px;
text-decoration: none;
font-weight: bold;
line-height: 18px;
border-radius: 5px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
-o-border-radius: 5px;
color: #999999;
background-color: #515151;
} .overlay .toolbar a.close span {
color: #818181;
} .overlay .toolbar a.close:hover,
.overlay .toolbar a.close:hover span {
background-color: #b90900;
color: #fff;
}
JavaScript
function openOverlay(olEl) {
$oLay = $(olEl);
if ($('#overlay-shade').length == 0)
$('body').prepend('<div id="overlay-shade"></div>');
$('#overlay-shade').fadeTo(300, 0.6, function() {
var props = {
oLayWidth : $oLay.width(),
scrTop : $(window).scrollTop(),
viewPortWidth : $(window).width()
};
var leftPos = (props.viewPortWidth - props.oLayWidth) / 2;
$oLay
.css({
display : 'block',
opacity : 0,
top : '-=300',
left : leftPos+'px'
})
.animate({
top : props.scrTop + 40,
opacity : 1
}, 600);
});
}
function closeOverlay() {
$('.overlay').animate({
top : '-=300',
opacity : 0
}, 400, function() {
$('#overlay-shade').fadeOut(300);
$(this).css('display','none');
});
}
$('#overlay-shade, .overlay a').live('click', function(e) {
closeOverlay();
if ($(this).attr('href') == '#') e.preventDefault();
});
// Usage
$('#overlaylaunch-inAbox').click(function(e) {
openOverlay('#overlay-inAbox');
e.preventDefault();
});