Recently, I implemented a lightbox effect for images on my website. However, I encountered an issue where the lightbox was not centering properly in the window upon initial click. Instead, the lightbox would appear at the bottom of the page on the first click and only align correctly upon subsequent clicks.
First Time Clicking the Image:
Second Time Clicking the Image:
The first time caused alignment issues. The second time did not have any alignment problems (without reloading the page). Javascript:
<script>
jQuery(document).ready(function() {
jQuery("img").click(function() {
var img_path;
if ($(this).parent('a').length) {
img_path = $(this).parent('a').prop('href');
}
else
{
img_path = $(this).attr('src');
}
jQuery(".cplightbox1").html(jQuery("<img>").attr("src", img_path));
jQuery(".cpoutter").css('display', 'block');
jQuery('.cpoutter').animate({'opacity': '1'});
//jQuery('.lightbox').animate({'opacity':'1.00'});
var cplightbox = document.getElementsByClassName('cplightbox')[0];
var cpoutter = document.getElementsByClassName('cpoutter')[0];
cplightbox.style.marginTop = ((cpoutter.offsetHeight / 2) - (cplightbox.offsetHeight / 2)) + "px";
return false;
});
});
</script>
HTML CODE:
Here is the Fiddle http://jsfiddle.net/rCUGD/7/
This script works fine on jsfiddle.net, so there might be an issue with the implementation on my website.
I'm unsure where I went wrong.
EDITED:
Thanks to @JustAnil, here is how the lightbox should look after the second click:
After the second click, it should display normally like this.