Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
142
rated 0 times [  144] [ 2]  / answers: 1 / hits: 15951  / 13 Years ago, tue, june 21, 2011, 12:00:00

I was wondering if there would be any reason this piece of code will not work...



top = $(this).find('ul').position().top;


It works in IE, Firefox, and Safari, however when I alert the output in Chrome it says DOM window object... I need an integer. Why would it alert out DOM window object?


More From » jquery

 Answers
167

Are you sure you're really alerting that top? Recall that top is a pre-existing global variable in browser-hosted JavaScript (it's window.top, the top-level window).



Update: Interesting, Chrome won't let you implicitly overwrite top (which is probably a good thing): Demo. Just declare your variable (always a good idea anyway) within whatever function that code is in (that code is in a function, right?), which will shadow it, and so that will work: Demo. E.g.:



var top = $(this).find('ul').position().top;


It's important to declare your variables, in order to avoid falling prey to the Horror of Implicit Globals. And as you've found in this case, avoiding globals is always best, as Chrome won't even let you use top as a global if you declare it (again to protect window.top).


[#91603] Monday, June 20, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
christianu

Total Points: 481
Total Questions: 124
Total Answers: 99

Location: Trinidad and Tobago
Member since Thu, Dec 1, 2022
2 Years ago
christianu questions
;