July 19, 2013

jQuery – css() not working properly in firefox

HowToPlease’s Question:

I am using .css() to get style from a element.
But in firefox .css() is not getting value of margin and padding from element.

Please see the fiddle:
http://jsfiddle.net/howtoplease/fMTsW/

This is my jquery code:

$(document).ready(function(){
    $('input').each(function(){
        this.value = $('h3').css(this.name);
    });
});

My html code

<h3 style="margin:20px;padding:20px;font-size:30px;font-family:'open sans';">
    I am heading 3
</h3>

<input name="margin" />
<input name="padding" />
<input name="font-size" />
<input name="font-family" />

The CSS tag ‘margin & padding’ is actually a shorthand for the four separate margin/padding values, top/left/bottom/right. Use css(‘marginTop’), etc. – note they will have ‘px’ on the end if you have specified them that way.

Use parseInt() around the result to turn it in to the number value.

<input name="margin-top" />
<input name="padding-top" />

OR

<input name="marginTop" />
<input name="paddingTop" />

This will give you the value. Using this technique you can get the value of margin and padding.

This is happening because properties like margin and padding are short hand property and jQuery cannot give you these values you have use independant values such as margin-top and margin-right.

Moreover, properties with multiple words like margin-top should be accessed using marginTop i.e First letter of second word should be capital.

For a full set of values:

<input name="marginTop" />
<input name="marginRight" />
<input name="paddingTop" />
<input name="paddingRight" />
<input name="fontSize" />
<input name="fontFamily" />

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!