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

I am trying to determine the top offset of an element and the console logs an error, even though JQuery

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745088257a4610535.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信