Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find element height, including margin

I'm making a simple and fun drawing app, and in it the structure is as follows:

  • Header
  • Canvas
  • Footer

I'm trying to get the canvas to be the full height of the window, minus the header height and footer height.

I've tried multiple things like:

canvas.height = window.height - (document.getElementById("header").offsetHeight + document.getElementById("footer").offsetHeight);

And I've even tried:

function getHeight(id) {
    id = document.getElementById(id);
    return id.offsetHeight + id.style.marginTop + id.style.marginBottom;
}

canvas.height = window.height - (getHeight("header") + getHeight("footer"))

But to no avail. In the console id.style.marginTop just returned an empty string, although its marginTop is set in the css... just not set specifically to marginTop, it's set as margin: 8px 0 8px 0;

Is there any way, without using jQuery, to obtain the rendered height of an element, including margin?

I'm assuming we'd have to separate the margin: 8px 0 8px 0; into separate variables, using id.style.margin... but I'm just not sure how to separate it.

like image 789
Elegant.Scripting Avatar asked Apr 09 '15 20:04

Elegant.Scripting


1 Answers

function outerWidth(el) {
  var width = el.offsetWidth;
  var style = getComputedStyle(el);

  width += parseInt(style.marginLeft) + parseInt(style.marginRight);
  return width;
}

this does exactly what jquery's outerwidth is doing, scratched from ::http://youmightnotneedjquery.com/ might be interteresting for further develpoment

EDIT: in ie8 you have to use el.currentStyle[prop] instead of getComputedStyle(el);

like image 109
Alexis Peters Avatar answered Sep 22 '22 21:09

Alexis Peters