treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] JQuery Css width of a div returns undefined.

  • Hey, so I'm having trouble understanding why a JQuery variable is retuning undefined. This is what I have in my HTML:

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Demo</title>
    <link href="css/style.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/testscript.js"></script>
    </head>
    <body>
    <div id="box"></div>
    <input type="button" id="clickme" value="Click Here!" />
    </body>
    </html>


    CSS:


    #box {
    background-color: #FF0000;
    width: 200px;
    height: 100px;
    }


    and Javascript:

    var cssWidth = $('#.box').css('width');

    alert(cssWidth);


    However, when I reload the page, the alert that gets triggered comes back saying "undefined" I've checked all the syntax out and it looks like everything is all good. Anyone see where the problem is? This is running on my localhost, but I do have JQuery called in my HTML, so it should work. I'm also pretty new at this stuff, so any help would be appreciated.
    Thanks,
    Noel
  • var cssWidth = $('#box').css('width');

    no dot in the selector
  • Ok, fixed that, but it's still returning as undefined. This is what the javascript looks like now, but the HTML and CSS are the same as above.

    var cssWidth = $('#box').css('width');

    alert(cssWidth);
  • fixed it. apparently this is the wrong way to do it:
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Demo</title>
    <link href="css/style.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/testscript.js"></script>
    </head>
    <body>
    <div id="box"></div>
    <input type="button" id="clickme" value="Click Here!" />
    </body>
    </html>

    and this is the RIGHT way:
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Demo</title>
    <link href="css/style.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
    <div id="box"></div>
    <input type="button" id="clickme" value="Click Here!" />
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/testscript.js"></script>
    </body>
    </html>

    if you do do it the first way, by loading the scripts in the head, you need to call
    $(document).ready(function(){
    //Code goes here.
    });

    in your script file.
  • You should pretty much always use $(document).ready though, as it ensures that the DOM is completely loaded before you start manipulating it with javascript.
  • Good to know. Thank you! :D