5

I am using height() / width() method but its returning value without it's padding and margin values. I am not having problem to calculate total with / height values.

This way is working but my problem is; its too long to calculate all of them. Is there a way to calculate these with less code without bugs ?

Here is jsFiddle example.

jQuery:

var ele = $('div');

var eleW = ele.width();
var eleH = ele.height();

alert(eleW);//returning 200
alert(eleH);//returning 100

var eleMR = parseInt(ele.css('margin-right'));
var eleML = parseInt(ele.css('margin-left'));
var eleMT = parseInt(ele.css('margin-top'));
var eleMB = parseInt(ele.css('margin-bottom'));

var elePR = parseInt(ele.css('padding-right'));
var elePL = parseInt(ele.css('padding-left'));
var elePT = parseInt(ele.css('padding-top'));
var elePB = parseInt(ele.css('padding-bottom'));

var eleTotalWidth = eleMR + eleML + elePR + elePL + eleW;
var eleTotalHeight = eleMT + eleMB + elePT + elePB + eleW;

alert(eleTotalWidth);//returning 147
alert(eleTotalHeight);//returning 122

css:

div {
       float:left; width:100px; height:200px; background-color:#000;
       margin:5px 3px 2px 4px; padding:10px 20px 5px;
     }​
Barlas Apaydin
  • 7,233
  • 11
  • 55
  • 86

1 Answers1

11

Use outerWidth(); and outerHeight();

var ele = $('div');

var eleW = ele.outerWidth(true);
var eleH = ele.outerHeight(true);
Vins
  • 8,849
  • 4
  • 33
  • 53
  • http://jsfiddle.net/B7fMW/7/ this is calculating without margins, but its still lesser code than mine (: – Barlas Apaydin Jul 26 '12 at 08:57
  • As per @WouterH we need to pass true as mentioned in the documentation. Pass true it will include your margin also. – Vins Jul 26 '12 at 09:02
  • 4
    @Vins: that makes your answer correct. I'll remove my answer as you was the first while I was still playing with the fiddle :) – huysentruitw Jul 26 '12 at 09:06
  • and note that, this way also returns border values. – Barlas Apaydin Jul 26 '12 at 10:01
  • 1
    @Vins - great stuff. Thank you very much for posting that. Even though it was a while back, it came in very handy for me. Thanks. – Ace Apr 29 '13 at 14:09