teelou teelou - 7 months ago 19
Javascript Question

get the margin size of an element with jquery

How can I get the properties of an element with jquery? I want to get the size of the margin of a div in particular.

I have set the style of the div in a .css file, for instance,

.item-form {
margin:0px 0px 10px 0px;
background: blue;
}


the html,

<form>
...

<div class="item-form">
<textarea class="autohide"></textarea>
</div>

...

</form>


I tried with this code, but it fails obviously,

$(".autohide").each(function(){

var $this = $(this);
alert($this.parents("div:.item-form").css("margin"));


});


any ideas? thanks.

Answer

The CSS tag 'margin' is actually a shorthand for the four separate margin 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.

NB. As noted in another answer, the order of the shorthand 'margin' tag is: top right bottom left - the above list was not written in a way intended to be the list order, just a list of that specified in the tag.