Custom jQuery “lightbox”
One thing I learned this week was how to make my own “lightbox” in jQuery. I’ve always used tools like thickbox or lightbox, but I’ve never actually needed to change some of it’s functionality. Or for that matter, change the look of it other than a quick color swap or two.
The below code is the main HTML of the light box. It’s quite fantastic because anything inside the “modal-container” div can be styled exactly how you need it without the over-extensive code written for other light-boxes:
Hi I'm a lightbox
Click me to open modal box
Here’s a little CSS to make it invisible on default and set the overlay and container colors:
#overlay, #modal-container{display:none; }
#overlay{background:#000; width:100%; height:100%; position:fixed; top:0; left:0; }
#modal-container{background:#fff; width:820px; height:420px; border:3px #ccc solid; top: 10%; left:50%; margin:0 0 0 -420px; position:fixed;filter:alpha(opacity=100); opacity:1;}
The below code is the main jQuery commands that makes the lightbox appear and go away:
$(document).ready(function(){
$('#overlay').click(function() {
$('#overlay').fadeOut();
$('#modal-container').fadeOut();
return false;
});
$('.modeBoxLink').click(function() {
$('#overlay').fadeIn(1000);
$('#modal-container').fadeIn(1000);
return false;
});
});
So if you have a link on the main page with class set to “modeBoxLink” it will open up the box you just created! Good for whatever content you need in such a window. ((Don’t forget to include the jQuery library))
All together:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#overlay').click(function() {
$('#overlay').fadeOut();
$('#modal-container').fadeOut();
return false;
});
$('.modeBoxLink').click(function() {
$('#overlay').fadeIn(1000);
$('#modal-container').fadeIn(1000);
return false;
});
});
</script>
<style>
#overlay, #modal-container{display:none; }
#overlay{background:#000; width:100%; height:100%; position:fixed; top:0; left:0; }
#modal-container{background:#fff; width:820px; height:420px; border:3px #ccc solid; top: 10%; left:50%; margin:0 0 0 -420px; position:fixed;filter:alpha(opacity=100); opacity:1;}
</style>
Hi I'm a lightbox
Click me to open modal box