gespinha
gespinha

Reputation: 8487

Logging an error with offset().top, why?

I am trying to determine the top offset of an element and the console logs an error, even though JQuery's documentation says it should be written like this:

$('.myObject').offset().top

Error:

Uncaught TypeError: Cannot read property 'top' of undefined

Why does this happen? Any solution for the problem?

Upvotes: 1

Views: 6029

Answers (2)

Saturnix
Saturnix

Reputation: 10564

This usually happens because $('.myObject') returns nothing. To protect your code from crashing, check if the element exists before calling .offset().top

var myObj = $('.myObject');
if (myObj.length){
   myObj.offset().top
}

Since .top is a property and not a method, it is not handled by jQuery and, hence, will crash your script if it is not existing.

Upvotes: 4

SidOfc
SidOfc

Reputation: 4584

You'll have to check if the element exists.

e.g.

var myObjExists = $('.myObject').length > 0 ? true : false;

if you then console.log(myObjExists);, it should return true or false.

From here you can do some errorhandling to why it does not exist.

If you need more details, please also post the HTML that this code points to.

Upvotes: 1

Related Questions