Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript JQuery Css width of a div returns undefined.

  • This topic is empty.
Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #39300
    Noel Forte
    Participant

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





    Demo








    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

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

    no dot in the selector

    #107640
    Noel Forte
    Participant

    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);
    #107651
    Noel Forte
    Participant

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





    Demo








    and this is the RIGHT way:





    Demo








    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.

    #107709
    Noel Forte
    Participant

    Good to know. Thank you! :D

Viewing 5 posts - 1 through 5 (of 5 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.