I have created a popup box class. Each popup can have a variable content, and appears in a variable position, depending on where the cursor is when it is open, so that the popup seems to come out from the clicked link or button.
The problem is that the popup may be partially outside the screen, if the cursor is too close to the borders. To adjust the position I need the width and height of the popup.
I tried this:
$("#" + div_id).show(400);
var off = $("#" + div_id).offset();
var t = off.top;
var l = off.left;
var h = $("#" + div_id).outerHeight();
var w = $("#" + div_id).outerWidth();
var docH = $(document).height();
var docW = $(document).width();
alert("t = "+ t + ", h = " + h + ", w " + w + ", l "+ l + ", docH " + docH + ", docW " + docW);
if ((t + h) > docH) {
var h_diff = (t + h) - docH; //difference (how much is hidden?)
var new_top = Math.max(10, t - h_diff - 10); //move it of the needed amout + 10 margin (but don’t go further than 10 from top border)
$("#" + div_id).css("top", new_top);
}
if ((l+ w) > docW) {
var w_diff = (l + w) - docW; //difference (how much is hidden?)
var new_left = Math.max(10, l - w_diff - 10); //move it of the needed amout + 10 margin
$("#" + div_id).css("left", new_left);
}
The problem is that outerWidth() and outerHeight do fail, actually, because since I use the animated version of show(), the retrieved height and width are minimal. I’m quite sure that’s the reason, because everything works if I show the div immediately. Also, adding the alert to see what’s happening, I’ve found out that the popup appear only after the alert with the animation (and the alert shows minimal width and weight), while if do not add a duration to show() the popup is shown first, the the alert box appears, showing the correct values.
Any ideas?
Since you are already using jQuery you can use the .poisition() method to accomplish what you are trying to do.
http://jqueryui.com/demos/position/
Hope this helps