I have an application that generates div boxes dynamically. The boxes are overlapping each other, and moved 15px down and to the right.
However, when the bottom of a box hits the bottom of the page I want the next box to turn up on the top on the page. The same goes for when the right side of a box hits the right side of the page (ie. the boxes shouldn’t be able to go outside the page).
Below is my code, but it doesn’t work as I want. The boxes gets “out of bounds” on the right side before turning up on the left side, and regarding the bottom it’s not really right either. I guess there is a better way to accomplish this, I just don’t know what it is.
var win = $('<div/>', {
'class': 'window',
'width': this.width,
'height': this.height
}).appendTo('#container');
var containerHeight = $('#container').height();
var maxBottom = (desktopHeight / 2);
var containerWidth = $('#container').width();
var maxRight = desktopWidth;
var prev = win.prev('.window');
if (prev.length > 0) {
win.offset({
left: prev.offset().left + 15,
top: prev.offset().top + 15 });
if (prev.offset().top >= maxBottom){
win.offset({
top: 10
});
}
if (prev.offset().left >= maxRight){
win.offset({
left: 0
})
}
}
You can check if the element’s
.offset().topproperty plus the element’s.height()are equal or greater than the.height()if the document: