Search code examples
javascriptjqueryobject-literal

Javascript Object Literals and jQuery


I've updated the script here to give a better example. For $header I've got an anonymous function now returning $("#header"). Although this works I'm sure its not efficient as it calls $header every time it's used - so its the same as just using $("#header") throughout the code.

What I really want is to store $("header") in a variable. When I try to do this with $header2 (below) it fails. #header is red not blue.

When I use firebug to output lib.page.$header2.selector is correctly displays #header. As you can see the script which calls lib.page.init is at the bottom of the DOM.

Any ideas?

<script type="text/javascript">

        var lib = {
            page : {

                $header  : function() { return $("#header")},
                $header2 : $("#header"),

                init: function() {

                    lib.page.$header().css("background","red");
                    lib.page.$header2.css("background","blue");
                    console.log(lib.page.$header2.selector);

                }

            }
        }

</script>
</head>
<body>

    <div id="wrapper">
        <div id="header">
            <em>Example!</em>
        </div>  
    </div>      

    <script type="text/javascript">
        $(function() { lib.page.init(); });
    </script>

</body>

Solution

  • "This happens because the variables are instantiated at the time the script is interpreted. So at the time of the parser gets to the script the $("#header") isn't in the DOM yet."