jQuery looping through open dialogs to get/update position of each
I am trying to make the jQuery dialogs stay in their position relative to the window size, so for instance:
- If the original viewport width is 900px and there are 2 dialogs, one at 100,100 and another at 450,200
- When the window is resized to say 1200px, the first dialog would be 400,100 and the second at 750,200
I currently have this code handling the window resize, but it doesn't update the dialog positions:
jQuery(window).resize(function() {
widthCompensation = getBrowserWidths();
jQuery(".dialog-class").each(function() {
var myPosition = jQuery(this).dialog("option", "position");
var newLeft = parseInt(myPosition.context.offsetLeft+widthCompensation);
var newTop = parseInt(myPosition.context.offsetTop);
jQuery(this).dialog("option", "position", [newLeft,newTop]);
});
});
Any help would be greatly appreciated!
Modified code:
function getBrowserWidths() {
var standardWidth = 990;
var actualWidth = parseInt(jQuery(window).width());
var ret = (actualWidth-standardWidth)/ 2;
return(ret);
}
var leftPositions = new Array();
var widthCompensation = getBrowserWidths();
jQuery(window).resize(function() {
widthCompensation = getBrowserWidths();
jQuery(".target-class").each(function(i) {
var newLeft = leftPositions[i]+widthCompensation;
console.log(newLeft);
jQuery(this).css({"left": newLeft+"px"});
});
});
//loop through draggables to get their initial positions
jQuery(".target-class").each(function(i) {
v开发者_如何学运维ar myPosition = jQuery(this).offset();
leftPositions[i] = myPosition.left;
});
Using this in the each, it quite worked for me (if the dialog doesn't reach the corner of the browser.
var myPosition = $(this).offset();
var newLeft = myPosition.left+widthCompensation;
var newTop = myPosition.top;
$(this).dialog("option", "position", [newLeft,newTop]);
Hope it helps ;)
For the each, you can use the Index (here i),
var newLeft = new Array();
var newTop = new Array();
$(".dialog-class").each(function(i) {
var myPosition = $(this).offset();
var newLeft[i] = myPosition.left+widthCompensation;
var newTop[i] = myPosition.top;
$(this).dialog("option", "position", [newLeft[i],newTop[i]]);
});
Didn't test it so not 100% sure, but here is the idea.
精彩评论