Homer Homer - 1 month ago 16
jQuery Question

Uncaught ReferenceError: x is not defined, when trying to return object from function

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

Answer

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        // ***
    };
}