What you're doing won't work, I'm afraid, as you attach onclick handlers to all of the images, but also to your document's body element.
That means, that as soon as you click an image, the opacity class will be added to the body, by the first onclick handler, then it will be immediately removed by the second one.
A more rational approach would be to create a <div> element to be your opacity layer.
When a user then clicks on a link, you can display this div and blend in the image on top of it.
You can attach an onclick handler to the opacity div, so that it hides itself and the image being displayed when the user clicks on it.
I've made a demo for you to play around with here: http://hibbard.eu/blog/pages/lightbox-demo/
You can exit the lightbox by clicking anywhere that's not the image.
Here's the code:
HTML Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Lightbox demo</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<style>
#black_overlay{
display: block;
position: absolute;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: black;
z-index:1001;
-moz-opacity: 0.8;
opacity:.80;
filter: alpha(opacity=80);
}
#image {
position:relative;;
border: 16px solid white;
z-index:1002;
}
</style>
</head>
<body>
<div id="lightbox">
<a href="lolcat.jpg">Display image in lightbox</a>
</div>
<script>
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
return this;
}
$('document').ready(function () {
$('#lightbox a').click(function(){
$('<div>',{
id : 'black_overlay',
click: function(){
$(this).remove();
$('#image').remove();
}
}).insertBefore('#lightbox');
$('<img>',{
id: 'image',
src: $(this).attr('href'),
load: function() {
$(this).insertAfter('#lightbox').center();
}
})
return false;
});
});
</script>
</body>
</html>
I cannot take credit for the centre function. I found it here: http://www.queness.com/code-snippet/...n-using-jquery
Also, I found this post useful: http://stackoverflow.com/questions/8...-to-open-a-div
Bookmarks