I am trying to code a simple lightbox effect that I can use for multiple images on the same page. (Click a link, image shows up on with the website opaque in the background.) I found a nice little Javascript, but it only works for a single image on the page. I know my HTML and CSS, but I'm struggling to find a clean, simple solution for what should be a simple function. (Unfortunately, I'm not a Javascript coder, but I usually can modify scripts I find to work for what I need...this is just beyond my scope!)
Here's my Javascript:
window.document.onkeydown = function (e)
{
if (!e){
e = event;
}
if (e.keyCode == 27){
lightbox_close();
}
}
function lightbox_open(){
window.scrollTo(0,0);
document.querySelector('.light').style.display='block';
document.querySelector('.fade').style.display='block';
}
function lightbox_close(){
document.querySelector('.light').style.display='none';
document.querySelector('.fade').style.display='none';
}
After doing some research, and I changed the original getElementById
to querySelector
since I need to apply this to multiple images. But I'm thinking I need to switch back to ID, and possibly use numbered IDs to differentiate my images. But I'm not sure how to use one function for multiple instances.
My CSS is:
.fade {
display: none;
position: fixed;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: black;
z-index:1001;
-moz-opacity: 0.8;
opacity:.80;
filter: alpha(opacity=80);
}
.light {
display: none;
position: absolute;
top: 20%;
left: 50%;
width: auto;
height: auto;
margin-left: -150px;
margin-top: -100px;
border: 2px solid #FFF;
background: #FFF;
z-index:1002;
overflow:visible;
}
I haven't perfected the CSS, but I'm not worried about it at this point. I just need to get the Javascript working first.
And my HTML is something like this:
<a href="#" onclick="lightbox_open();">Photo 1</a>
<div class="light">
<a href="#" onclick="lightbox_close();"><img src="portfolio/print/hwtc/bcard-MUC.jpg" alt="" /></a>
</div>
<div class="fade" onClick="lightbox_close();"></div>
<br />
<a href="#" onclick="lightbox_open();">Photo 2</a>
<div class="light">
<a href="#" onclick="lightbox_close();"><img src="portfolio/print/hwtc/bcard-CUN.jpg" alt="" /></a>
</div>
<div class="fade" onClick="lightbox_close();"></div>
Like I said, this isn't my Javascript; I'm just in over my head trying to modify it for my needs. There's got to be a simple way to achieve this, but I don't know enough Javascript coding to do it myself. I probably need an array or something?? Can someone please help a girl out?? =) Thanks!