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!
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".
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With