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 );
}

Beginning jQuery

I’m working on a game and I think I could use some jQuery to make it easier to write. So I visited the jQuery Learning Center to get an overview of the library.

There are lots of examples of the code, but I need to actually write code to see how it works. So I wrote a bunch of code to follow along with the examples that they give. It might be useful to others, so here it is. All of the code is in the php file so if you view source, you will have everything I used.