SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Member jojolina's Avatar
    Join Date
    Feb 2008
    Location
    amsterdam, Netherlands
    Posts
    13
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    strange syntax in Novice to Ninja to set css property?

    Dear forum people,
    I am working through the book jQuery, Novice to Ninja. at page 88 i saw a piece of code that does not seem logic to me:
    They want to set css property 'width'.

    i see in the code:

    divTwo.css('width', divTwoWidth + 'px');

    earlier in the book i learned that if you want to set css properties, i should expect a syntax like this:

    divTwo.css(
    {'width':'divTwoWidth + 'px''}); or divTwo.css('width', 'divTwoWidth + 'px'');

    i do not understand why there are no '' around the value, the divTwoWidth ?

    Thanks for any help,

  2. #2
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,039
    Mentioned
    152 Post(s)
    Tagged
    2 Thread(s)
    divTwoWidth is a variable, that has value set earlier. When setting the width of this element, you want to set it to the value recorded earlier in the divTwoWidth variable. To do that, you need to access the variable itself. If you put the variable in quotes, you get a string with the value 'divTwoWidth', which is something else entirely.

    Code javascript:
    var divTwoWidth=200;
    divTwo.css('width', divTwoWidth + 'px');

    That will set the width of divTwo, because the value of divTwoWidth is 200.

    Had you used (incorrect) the string variant, you'd have

    Code javascript:
    var divTwoWidth=200;
    divTwo.css('width', 'divTwoWidth + px');

    set the width to 'divTwoWidth', but 'divTwoWidth' is not a number, so the expression is wrong (and will probably set the width to 0 since the string 'divTwoWidth' is 0 when cast to an integer).

    Does that make sense?
    Rémon - Hosting Advisor

    Minimal Bookmarks Tree
    My Google Chrome extension: browsing bookmarks made easy

  3. #3
    SitePoint Member jojolina's Avatar
    Join Date
    Feb 2008
    Location
    amsterdam, Netherlands
    Posts
    13
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks a lot! Now i know how to use a variable as a value to set a css propterty. Thanks for good explanation.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •