3

I just want to get the scrollTop of document and use the code from this answer. But what I get is a 'Window' object. I have tested with IE 10, Chrome and Firefox. Here is my code:

    var doc = document.documentElement, body = document.body;
    var left = (doc && doc.scrollLeft || body && body.scrollLeft || 0);
    var top = (doc && doc.scrollTop  || body && body.scrollTop  || 0);

    scroll = {
        top: (doc && doc.scrollTop  || body && body.scrollTop  || 0),
        left: (doc && doc.scrollLeft || body && body.scrollLeft || 0)
    };


    console.log(scroll.top); // return 0
    console.log(top); // return object 'Window'

I think it's a simple question but I can't figure out why it will return an object.

Community
  • 1
  • 1
Cedric
  • 95
  • 2
  • 9

2 Answers2

3

Your variable top is in the window scope. I can reference it with window.top or window.left. The problem with window.top is already defined. window.top refers to the top most window in the hierarchy. The browser is not letting you set that variable.

You would need to define it as a different variable or make change the scope so it does not conflict with the global [window] namespace.

epascarello
  • 204,599
  • 20
  • 195
  • 236
  • +1 Nice thinking, I thought it was a scope issue. It makes sense that `window.top` is not writeable, so if all that code is in the global scope that would cause it as well (and is a more accurate answer based on the OP's code). – Paul Aug 28 '13 at 16:53
  • Yes, just like you said. Thanks. – Cedric Aug 29 '13 at 14:22
1

It could be that your console.log is not within an inner scope of your var top declaration.

When you reference top you would not be referring to the variable you declared, but instead to window.top:

console.log(top); // global variable `window.top`: window object

;(function(){
  var top = 0;

  console.log(top); // local variable `top`: 0

})();

console.log(top); // global variable `window.top`: window object
Paul
  • 139,544
  • 27
  • 275
  • 264