Grow your CSS skills. Land your dream job.

JQuery Css width of a div returns undefined.

  • # August 9, 2012 at 6:27 pm

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

    < !doctype 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

    # August 9, 2012 at 6:44 pm
    var cssWidth = $('#box').css('width');

    no dot in the selector

    # August 10, 2012 at 12:50 am

    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);
    # August 10, 2012 at 12:58 am

    fixed it. apparently this is the wrong way to do it:

    < !doctype html>












    and this is the RIGHT way:

    < !doctype 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.

    # August 10, 2012 at 3:50 am

    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.

    # August 10, 2012 at 6:55 pm

    Good to know. Thank you! :D

Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".