Reputation: 255
I'm having some issues with a particular script. I found a simple modal window script that I'm trying to implement. The original functionality was that it would simply hide/show the window div with its "static" content. This is nice, but I needed the ability to be able to specify the content on the fly. So I changed things up by allowing the .load() function to be used to "inject" the div's content and then the script would simply show the window as normal. However, when the modal is closed, I emptied the contents of the div using .empty() to allow the ability to add different content on the fly depending on the value of an attribute in the link used to open the model window.
Everything works just fine except the window is not centered in the middle of the screen if I use the .load() function as opposed to just hard-coding the <embed>
code into the div's content. If I hard-code the <embed>
object it centers just fine and looks awesome.
Obviously there's a discrepancy in the overall window height/width if the <embed>
object is injected into the div on the fly. I tried positioning the .load()
function before and after the script looks for the total width/height of the window div, but that doesn't seem to affect anything.
Any help would be greatly appreciated!!
Here's the script:
$(document).ready(function() {
//select all the a tag with name equal to modal
$('a[name=modal]').click(function(e) {
//Cancel the link behavior
e.preventDefault();
//Get the A tag
var id = $(this).attr('href');
//Get source file for AJAX request
var source = $(this).attr('src');
//If source is set, send ajax request, and then load content into window
if(source != undefined) {
$('.window').load(source);
}
//Get the screen height and width
var maskHeight = $(document).height();
var maskWidth = $(window).width();
//Set heigth and width to mask to fill up the whole screen
$('#mask').css({'width':maskWidth,'height':maskHeight});
//transition effect
$('#mask').fadeIn(1000);
$('#mask').fadeTo("slow",0.8);
//Get the window height and width
var winH = $(window).height();
var winW = $(window).width();
//Set the popup window to center
$(id).css('top', winH/2-$(id).height()/2);
$(id).css('left', winW/2-$(id).width()/2);
//transition effect
$(id).fadeIn(2000);
});
//if close button is clicked
$('.window .close').click(function (e) {
//Cancel the link behavior
e.preventDefault();
$('#mask').fadeOut("slow");
$('.window').fadeOut("slow", function() {
$(this).empty();
});
});
//if mask is clicked
$('#mask').click(function () {
$(this).fadeOut("slow");
$('.window').fadeOut("slow", function() {
$(this).empty();
});
});
});
Upvotes: 0
Views: 551
Reputation: 2702
That's because load is triggering an AJAX request and your centering code is being run before the content is loaded. What you need to do is center the modal in the ajax complete handler.
$('.window').load(source,null,function(){ functionThatCentersModal() });
Upvotes: 1