javascript - Logging an error with offset().top, why? - Stack Overflow

admin2025-04-20  3

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?

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?

Share Improve this question edited Oct 25, 2013 at 7:12 zzlalani 24.4k16 gold badges47 silver badges73 bronze badges asked Oct 25, 2013 at 7:07 gespinhagespinha 8,50717 gold badges59 silver badges96 bronze badges 3
  • 1 what does $('.myObject').length returns? – Saturnix 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. – Abhitalks 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. – Saturnix Commented Oct 25, 2013 at 7:27
Add a ment  | 

2 Answers 2

Reset to default 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.

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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745088259a284269.html

最新回复(0)