position element correctly on screen
calculate the position of an element so that no part of it is outside of the viewport
by Richard Hunter
HTML
<div id="foo">
</div>
<div id="bar">
</div>
CSS
#foo {
background: red;
width: 100px;
height: 100px;
position: fixed;
left: 400px;
top: 200px;
}
JavaScript
function getElementWidth(element) {
return element.offsetWidth + 'px';
}
function getElementHeight(element) {
return element.offsetHeight + 'px';
}
function getElementLeft(element) {
return element.getBoundingClientRect().left + 'px';
}
function getElementTop(element) {
return element.getBoundingClientRect().top + 'px';
}
console.log(self.innerWidth)
const VERTICAL_PADDING = 10;
const HORIZONTAL_PADDING = 10;
function copyEl(el) {
const newEl = document.createElement('div');
newEl.style.position = 'fixed';
newEl.style.background = 'green';
let {left, top, width, height} = el.getBoundingClientRect();
newEl.style.width = width + 'px';
newEl.style.height = height + 'px';
width += HORIZONTAL_PADDING;
height += VERTICAL_PADDING;
const viewportWidth = self.innerWidth;
const viewportHeight = self.innerHeight;
if ((left + width) > viewportWidth) {
left = viewportWidth - width;
}
if ((top + height) > viewportHeight) {
top = viewportHeight - height;
}
newEl.style.left = left + 'px';
newEl.style.top = top + 'px';
newEl.style.opacity = 0.5;
return newEl;
}
bar.appendChild(copyEl(foo))