Heya Peeps,

Today one of my colleague was stuck in very basic Javascript function, in which he was trying to change the font-size of a paragraph by tweaking the CSS “font-size” property with the help of a Javascript function. His code was perfect but with one problem, that was proper reference of CSS property in Javascript. Generally we use the display property for hidding and showing various divs on pages, and we seek no conversion doing that. But when it comes to changing properties which have “-” in them, then we have to following a naming convention.javascript digimantgra1 CSS Properties To JavaScript Reference Conversion

Why javascript wont understand font-size

When you try to change the CSS property using the following piece of code, it wont actually change it. The reason behind this is that Javascript do not permit variable names which have “-” in them.

var font-size="myfont"; //is not a variable
var fontSize = "myfont" //is a variable
var fontsize = "myfont" //is a variable

document.getElementById('mypara').style.font-size="24px"; //bad statement
document.getElementById('mypara').style.fontSize="24px";  // works well 

So there is a rule defined for this sort of naming convention, that is, we actually replace the “-” sign with camelCase  type of  naming convention.  Few examples are :

background-color  ->>  backgroundColor
background-image  ->>  backgroundImage
background-position ->>   backgroundPosition
background-repeat   ->> backgroundRepeat
border-bottom-color ->> borderBottomColor
border-bottom-style ->> borderBottomStyle
border-bottom-width ->> borderBottomWidth
border-color ->> borderColor
border-left ->> borderLeft
border-left-color ->> borderLeftColor
border-left-style ->> borderLeftStyle
border-left-width ->> borderLeftWidth
border-right ->> borderRight
border-right-color ->> borderRightColor
border-right-style ->> borderRightStyle
border-right-width ->> borderRightWidth
border-style ->> borderStyle
border-top ->> borderTop
border-top-color ->> borderTopColor
border-top-style ->> borderTopStyle
border-top-width ->> borderTopWidth
border-width ->> borderWidth

So the rule is simple to follow. Any problems, just leave a comment icon smile CSS Properties To JavaScript Reference Conversion

Hope that helps,

Sachin Khosla

Share this post: