Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - css() not working properly in firefox

Tags:

jquery

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" />
like image 317
user007 Avatar asked Jul 19 '13 03:07

user007


3 Answers

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.

like image 177
Zahid Riaz Avatar answered Nov 09 '22 13:11

Zahid Riaz


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" />
like image 28
Starx Avatar answered Nov 09 '22 14:11

Starx


In your code in fiddle i tried changing the HTML.

From

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

To

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

and the values were set in the inputs value field correctly. This is because the margin in css is a keyword which set value of attributes like margin-right, margin-left,margin-top,margin-bottom to a value but it by itself is not a attribute.

like image 1
Suvi Murugan Avatar answered Nov 09 '22 12:11

Suvi Murugan