## Getting the position of elements on the screen

I have a game where I move a target and drop it on foils. I know where I put the foils, but I wanted to know where they are in relation to the window if the window is scrolled or resized. This isn’t exactly what I was needing, but it’s useful enough that I might need it in the future.


// Find the position of elements
function getOffset(element) {
element = element.getBoundingClientRect();
return {
left: element.left + window.scrollX,
right: element.right + window.scrollX,
top: element.top + window.scrollY,
bottom: element.bottom + window.scrollY
}
}
function whereAreTheFoils() {
// Find out where things are for initial setup and debugging
var foil0 = document.getElementById('foil_0');
var foil1 = document.getElementById('foil_1');
var foil2 = document.getElementById('foil_2');
var foil3 = document.getElementById('foil_3');
console.log('Foil 0 is at LR ' + getOffset(foil0).left + ', ' + getOffset(foil0).right );
console.log('Foil 0 is at TB ' + getOffset(foil0).top + ', ' + getOffset(foil0).bottom );

console.log('Foil 1 is at ' + getOffset(foil1).left + ', ' + getOffset(foil1).top );
console.log('Foil 2 is at ' + getOffset(foil2).left + ', ' + getOffset(foil2).top );
console.log('Foil 3 is at ' + getOffset(foil3).left + ', ' + getOffset(foil3).top );
}