1

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?

3
  • 1
    what does $('.myObject').length returns? Commented Oct 25, 2013 at 7:08
  • 2
    Are you sure it isn't $('#myObject')? Using a class selector may be returning a set instead of one element. Commented Oct 25, 2013 at 7:09
  • If called on a set, .offset() will return the offset of the first element so it should not crash anyway. Commented Oct 25, 2013 at 7:27

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Slight optimization: do var myObject= $('.myObject'); and then use myObject. This prevents jQuery from having to traverse the DOM twice, which is relatively very expensive.
Even thou optimization was out of the scope of the question (and my answer) I've updated accordingly. Thanks.
I think your update had a race condition with zzlalani, and you lost your changes.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.