Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

offset().top returning window object

Tags:

jquery

i can't get this through.

I need to get offset().top from a jquery object, this is my code

parentLi = $(element).parents("li");
parentLiOffset = parentLi.offset();
top = parentLiOffset.top;
left = parentLiOffset.left;
console.log(parentLiOffset);
console.log(top);
console.log(left);

And this is what console gives back:

Object { top=208, left=311}  
Window /demo/
311

as you can see, I can't manage to get the "top" value. I'm usinf firefox, if that makes any difference.

Thanks!

like image 666
monxas Avatar asked Mar 01 '12 13:03

monxas


3 Answers

The problem is that you haven't used the var keyword to declare your variables. top is a property of window (a read-only property, which is why your code doesn't overwrite it). Do this instead:

var top = parentLiOffset.top;
var left = parentLiOffset.left;

left works without var, because left is not a property of window. Your code creates a property of window named left and assigns the correct value to it. However, it is good practice to always use the var keyword to prevent variables leaking into the global scope.

The top property "returns a reference to the topmost window in the window hierarchy".

like image 63
James Allardice Avatar answered Sep 23 '22 23:09

James Allardice


You forgot to declare those variables locally.

Do this:

var top = ...
var left = ...

When you don't declare variables beforehand, they are treated as global properties. In this case, you're trying to write to the window.top property which is read-only.

Failing to declare variables beforehand is dangerous since it can produce unexpected results (as you saw for yourself).

like image 32
Šime Vidas Avatar answered Sep 23 '22 23:09

Šime Vidas


Is that the only code or have you got something betwin your definition of top and the consol.log.

And yes, it is a good thing getting used to writting "var" before your variable when you declare them.

like image 34
artragis Avatar answered Sep 25 '22 23:09

artragis