I’m currently attempting to make a custom lightbox-like feature on my website (www.slatewerner.com). My method thus far is to, on click, wrap the image in a div that is then positioned absolute, outside of the content flow, and with a half opaque grey background. All of my images, besides the landing image/state, are loaded via AJAX. The problem that I am facing is that I cannot access the newly loaded images with my ‘lightbox’ function.
My attempt can be found live here: http://www.slatewerner.com/index_3.1
How can I make the browser, jQuery, or whatever needs to, be aware that hese new images are in the DOM? Or how can I rewrite my function so that it is effective on newly loaded content?
My jQuery (only lightbox section):
$(document).ready(function(){
$('#content img').click(function(){
var img = this;
var width = img.clientWidth;
var height = img.clientHeight;
var imgWidth = -width/2;
var imgHeight = -height/2;
$(this).wrap('<div class="box"></div>');
$('.backdrop, .box').animate({'opacity':'.50'}, 300, 'linear');
$('.box').animate({'opacity':'1.00'}, 300, 'linear');
$('.backdrop, .box').css('display', 'block');
$('.box').css('margin-left', imgWidth);
$('.box').css('margin-top', imgHeight);
});
$('.close').click(function(){
close_box();
});
$('.backdrop').click(function(){
close_box();
});
});
function close_box()
{
$('.backdrop, .box').animate({'opacity':'0'}, 300, 'linear', function(){
$('.backdrop, .box').css('display', 'none');
});
}
My CSS (only lightbox section):
.backdrop {
position:absolute;
top:0px;
left:0px;
width:100%;
height:100%;
background:#000;
opacity: .0;
filter:alpha(opacity=0);
z-index:50;
display:none;
}
.box {
position:absolute;
top:50%;
left:50%;
background:#ffffff;
z-index:51;
padding:10px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-moz-box-shadow:0px 0px 5px #444444;
-webkit-box-shadow:0px 0px 5px #444444;
box-shadow:0px 0px 5px #444444;
display:none;
}
.close {
float:right;
margin-right:6px;
cursor:pointer;
}
Thanks,
-Slate
Use
.oninstead to bind your click even handler. This will ensure that the even gets bound for elements currently in the DOM and ones that are later dynamically inserted.