user5199117
user5199117

Reputation:

Why am I getting "Uncaught TypeError: Cannot read property 'body' of undefined"?

My JS file is simply

jQuery(function ( $ ) {
    // make elements with class 'same-height-as-width' have the self-explanatory property
    $(window).resize(function ( ) {
        $('.same-height-as-width').each( function ( ) {
            var thisElement = $(this);
            thisElement.height(thisElement.width());        
        });
    });

    window.onscroll = function () {

        var body = document.body; //IE 'quirks'
        var document = document.documentElement; //IE with doctype
        document = (document.clientHeight) ? document : body;

        if (document.scrollTop == 0) {
            alert("top");
        }
    };

});

and the line that is causing me trouble is var body = document.body; //IE 'quirks'. The error

Uncaught TypeError: Cannot read property 'body' of undefined

is printed to the console every time I scroll. And yet, when I type document.body into the console, the element shows up in the console, is not undefined. I've also tried moving the window.onscroll outside the jQuery(function ( $ ) but I get the same error.

Upvotes: 0

Views: 2479

Answers (1)

Amit
Amit

Reputation: 46341

That's because of JavaScript variable hoisting, but without confusing you to much, don't use "document" as a name for your variable

Upvotes: 2

Related Questions