1

I'm trying to create a function to get the positions of elements, but when I try to get the bottom offset it return not defined, what am I missing?

This is my attempt:

var myDiv = jQuery('.div');

function getOffset(el) {
    var off = jQuery(el).offset();
    return {
        left: off.left,
        right: off.left + el.outerWidth(),
        top: off.top,
        bottom: off.top + el.outerHeight(),
        hCenter: (bottom + top) /2,
        wCenter: (right + left) /2
    };
}

var myDivPosition = getOffset(myDiv);

console.log(
        "top = " + myDivPosition.top +
        "bottom = " + myDivPosition.bottom +
        "hCenter = " + myDivPosition.hCenter +
        "left = " + myDivPosition.left +
        "right = " + myDivPosition.right +
        "wCenter = " + myDivPosition.wCenter
        );

I get in the console:

Uncaught ReferenceError: bottom is not defined

Homer
  • 355
  • 1
  • 5
  • 17

1 Answers1

3

You're trying to use bottom and right variables you haven't declared. Note that using an unqualified bottom or right identifer doesn't in any way retrieve them from the object you're building (in fact, there is no reasonable way). So just do them up-front (you also need to refer to top and left on off):

function getOffset(el) {
    var off = jQuery(el).offset();
    var bottom = off.top + el.outerHeight();  // ***
    var right = off.left + el.outerWidth();   // ***
    return {
        left: off.left,
        right: right,                         // ***
        top: off.top,
        bottom: bottom,                       // ***
        hCenter: (bottom - off.top) /2,       // ***
        wCenter: (right - off.left) /2        // ***
    };
}
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875