The Main Part Box & JavaScript
Well previously I posted on the basics of creating a lightbox, I shall explain the code for one of my most basic creations as once you understand this you can take it a lot further.
So I shall start with the JavaScript:
function lightbox(id1){
if(document.getElementById(id1).style.display==”block”){
document.getElementById(id1).style.display=”none”;
document.getElementById(‘lightbox’).style.display=”none”;
}else{
document.getElementById(id1).style.display=”block”;
document.getElementById(‘lightbox’).style.display=”block”;
}
}
Essentiall all it is doing is checking if id1 is already open if its shown as a CSS display block it will close id1 and lightbox id, else it will open them.
This keeps the script nice and short no bloated effects like Lightbox2 or jQuery lightbox, now in your html all you need to do is:
<div id=”mybox” class=”lightbox” style=”display:none;”>
stuff you want in lightbox
<a href=”javascript:lightbox(‘mybox’)”>Close Lightbox</a>
</div>
You can see I’ve set display:none; this is very important just because we are hiding the box, yeah not good for the search engines but for now it works, when you get more advanced I would have a class called hide, and apply it to the div tag just to keep google happy.
Now to open it:
<a href=”javascript:lightbox(‘mybox’)”>Open Lightbox</a>
So all we’re passing the function is the box ID (mybox) which will then open and we can use the EXACT same link to close it again!
![]()
Centering the Lightbox
Well we have the basics we now want it to have some nice effects.
.lightbox{
position:fixed;
height:200px;
width:500px;
top:50%;
left:50%;
margin-top:-100px;
margin-left:-250px;
}
So we’re setting the box as fixed so it scrolls with the page, and to get the full effect of centering it you need to set a height and width but when you enter the more advanced stages of lightbox you can just get the dimensions through JavaScript.
Now the essential part centering the box, top 50% and left 50% and then half the width and height which you can then offset in the margin, making it centered!
The Grey Background
Okay not the hardest part but it has the biggest effect, you can either have a white lightbox or black.
All you need is:
<div id=”lightbox” style=”position:fixed; top:0px; left:0px; width:100%; height:100%; background-image:(‘images/grey.png’);”> </div>
Your png file just needs to be 50% opacity #000000 and saved as a transparent png, this will then open when the JavaScript is triggered.