Please review my first query project, it achieves the desired result, but am I doing it right?
window.onresize = centreBoxInViewport;
function displayLightBox(obj) {
// Get the path to the image
var path = obj.getAttribute("href");
// Create a new image, and set its source.
var image = new Image();
// The onload function must come before we set the image's src, see link for explanation.
// http://www.thefutureoftheweb.com/blog/image-onload-isnt-being-called.
// Anonymous function set to onload event, to make sure we only proceed if the image has been loaded.
image.onload = function() {
$('#image').attr("src", path)
centreBoxInViewport();
showOverlay();
// Bind the hide functions here, as the elements have now been loaded into the DOM.
$('#overlay').click(hideLightBox);
};
// Set the src, and show the image.
image.src = path;
}
function hideLightBox() {
fadeBox();
}
function showBox(){
$('#lightbox').fadeTo(200, 1);
}
function fadeBox(){
$('#lightbox').fadeTo(200, 0, function() {
$('#lightbox').hide();
hideOverlay();
});
}
function centreBoxInViewport() {
// Get the dimensions of the viewport.
height = $(window).height()
width = $(window).width();
// Position the box.
$('#lightbox').css('top', (height/2) - parseInt($('#lightbox').height())/2);
$('#lightbox').css('left', (width/2) - parseInt($('#lightbox').width())/2);
}
function showOverlay() {
$('#overlay').fadeTo(200, 0.5, function() { showBox() });
}
function hideOverlay() {
$('#overlay').fadeTo(200, 0, function() {
$('#overlay').hide();
});
}
HTML
<div id="overlay" style="display: none"></div>
<div id="lightbox" style="display:none">
<div>
<a href="off somewhere" id="close" onclick="hideLightBox();return false;"></a>
<img id="image" alt="" src="">
</div>
</div>
CSS
div#overlay { position: fixed; background-color:#000000; top: 0px; left: 0px; width: 100%; height: 100%; z-index: 99; }
div#lightbox { background-color: white; border: 5px solid white; z-index: 100; position: fixed; }
Thanks