I know there's been a few posts about centering a modal box div using JQuery but I have looked and looked for a solution to my problem, and I have my suspicions on what is going wrong but nothing I've tried seems to have solved it.
I have a photo gallery, I click on an image, it grabs the path to the image when it is clicked on and chucks into the modal div a little bit of html in the form of an image with the src corresponding to the image that was clicked. It then fades in this div and then calls the centering function on it which positions top and left positions in the CSS accordingly.
Basically, sometimes it works, other times it doesn't. By using Firebug I have narrowed it down to the fact that sometimes it returns the width of the div correctly (i.e the width and height of the image) and sometimes it just returns 0. I presume this is something to do with it running the script before the image inside the div has loaded perhaps? (And I have tried grabbing the height and width of the image instead of the div the image is in but that doesn't seem to make a difference.)
I'm new to Javascript and JQuery so there may well be bits of code that don't necessarily need to be there or I've done things a long winded way or something.
Enough of my gabbering, here is the Javascript.
$(document).ready(function () {
var status = 0;
function loadImagePop(img){
if(status==0)
{
$("#bgPop").css({"opacity": "0.5"});
$("#bgPop").fadeIn("slow");
$('#imgPop').html("<img src=\""+img+"\"/>");
$("#imgPop").fadeIn("slow");
status = 1;
}
}
function closeImagePop(){
if(status==1)
{
$("#bgPop").fadeOut("slow");
$("#imgPop").fadeOut("slow");
status = 0;
}
}
function centerPopup(){
width = $(window).width();
height = $(window).height();
divWidth = $("#imgPop").width();
divHeight = $("#imgPop").height();
leftPos = (width-divWidth)/2;
topPos = (height-divHeight)/2;
$("#imgPop").css({"top": topPos, "left": leftPos});
}
$(".box a").click(function(){
var img = $(this).attr("href");
loadImagePop(img);
centerPopup();
return false;
});
$("#bgPop").click(function(){
closeImagePop();
});
And here are the relevant CSS.
#bgPop {
display: none;
position: fixed;
height: 100%;
width: 100%;
top: 0;
left: 0;
background: #000;
z-index: 1;
}
#imgPop {
position: absolute;
display: none;
z-index: 2;
}
And here is the relevant HTML.
My thumbnails are as so (not really important I assume).
<div class="box">
<a href="img/allotment.jpg"><img src="img/allotmentSMALL.jpg" alt="allotment"/></a>
</div>
And my modal divs sit at the end of the body after all my other HTML like this.
<div id="imgPop"></div>
<div id="bgPop"></div>
And before anyone says, why don't you just use one the many premade things for this, well I like to do things myself, I won't learn properly otherwise. (Apologies if any of the formatting is a bit off)