Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

variables not getting set in document.ready

This is really odd. If I write my javascript in a $(document).ready() function my var $okRow = come back undefined in the console

but if I simple remove the document ready wrapper my var gets set.

does not work

$(document).ready(function(){
   var $okRow = $('.status-column:contains("OK")').parent();
    if ($('#show-important').prop("checked")) {
        $okRow.css("display", "none");
    } else {
        $okRow.css("display", "table-row");
    }

    $('input[name="group1[]"]').on("click", function() {
        if ($('#show-important').prop("checked")) {
            $okRow.css("display", "none");
        } else {
            $okRow.css("display", "table-row");
        }        
    });
});

works

var $okRow = $('.status-column:contains("OK")').parent();
    if ($('#show-important').prop("checked")) {
        $okRow.css("display", "none");
    } else {
        $okRow.css("display", "table-row");
    }

    $('input[name="group1[]"]').on("click", function() {
        if ($('#show-important').prop("checked")) {
            $okRow.css("display", "none");
        } else {
            $okRow.css("display", "table-row");
        }        
    });

2 Answers

Hi John,

When you have it inside a function then the variable is local to that function and not available in the global scope.

When you take it out then all of that code is global and accessible from the console.

If you need to check your $okRow variable for debugging purposes then this stackoverflow link has some information on setting a breakpoint in the debugger. http://stackoverflow.com/questions/13766371/console-access-to-javascript-variables-local-to-the-document-ready-function

This is so that you can halt execution of the function and then you should be able to access that variable from the console.

You're using this within a HTML page?