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?
$('#myObject')
? Using a class selector may be returning a set instead of one element.
– Abhitalks
Commented
Oct 25, 2013 at 7:09
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.