Box Collision
HTML
<div class="box">My Box</div>
CSS
html, body { width: 100%; height: 100%; }
body {
margin: 0;
padding: 0;
color: #fff;
font-family: Arial, Helvetica, Sans-serif;
font-size: 100%;
line-height: 1;
background-color: #393939;
overflow-x: hidden;
}
.box {
position: absolute; /* absolute vs fixed */
bottom: -150px;
right: -150px;
width: 300px;
height: 300px;
color: #fff;
line-height: 300px;
text-align: center;
text-transform: uppercase;
background-color: #f00;
}
JavaScript
elemCollision($('.box'));
function elemCollision(el) {
// Viewport Width and Height
var viewportW = window.innerWidth;
var viewportH = window.innerHeight;
// Element Width and Height
var width = el.innerWidth();
var height = el.innerHeight();
// Element Position: top, right, bottom, left
var top = el.offset().top;
var left = el.offset().left;
var right = (viewportW - left) + viewportW;
var bottom = (viewportH - top) + viewportH;
// Amount Element is Off Screen
var offScreenX = (viewportW - left) - width;
var offScreenY = (viewportH - top) - height;
// Position Element 100% on Screen
var placementX = (viewportW - left) - Math.abs(offScreenX) - getScrollBarWidth() * 2;
var placementY = (viewportH - top) - Math.abs(offScreenY);
var scrollbar = getScrollBarWidth();
// Assign New X and Y Placement Values
$('.box').css({ bottom: placementY, right: placementX });
$('body').append(
'<div style="padding: 10px; font-size: 0.80em; line-height: 1.25em;">-----' + '<br/>' +
'Placement Top: ' + top + '<br/>' +
'Placement Right: ' + right + '<br/>' +
'Placement Bottom: ' + bottom + '<br/>' +
'Placement Left: ' + left + '<br/>' +
'Box Width: ' + width + '<br/>' +
'Box Height: ' + height + '<br/>' +
'Viewport Width: ' + viewportW + '<br/>' +
'Viewport Height: ' + viewportH + '<br/>' +
'Off-screen X: ' + offScreenX + '<br/>' +
'Off-screen Y: ' + offScreenY + '<br/>' +
'New Placement X: ' + placementX + '<br/>' +
'New Placement Y: ' + placementY + '<br/><br/>' +
'Scrollbar width: ' + scrollbar + '<br/>' +
'-----</div>'
);
}
function getScrollBarWidth () {
var $outer = $('<div>').css({visibility: 'hidden', width: 100, overflow: 'scroll'}).appendTo('body'),
widthWithScroll = $('<div>').css({width: '100%'}).appendTo($outer).outerWidth();
$outer.remove();
return 100 - widthWithScroll;
};