Element Dimensions


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. //get current dimensions and position of an element
  2. //usage: var dims = new ElementDimensions(elementToMeasure);
  3. function ElementDimensions(elem)
  4. {
  5. this.inner = { //content and padding; gives 0 for inline elements (you can use scrollWidth/Height if it's inline)
  6. width: elem.clientWidth,
  7. height: elem.clientHeight
  8. };
  9. this.outer = { //everything (content, padding, scrollbar, border)
  10. width: elem.offsetWidth,
  11. height: elem.offsetHeight
  12. };
  13. this.scroll = {
  14. //width & height of entire content field (including padding), visible or not
  15. //incorrect in Opera; it doesn't include the padding
  16. width: elem.scrollWidth,
  17. //if there are no scrollbars, IE gives the actual height of the content instead of the height of the element
  18. height: elem.scrollHeight<elem.clientHeight ? elem.clientHeight : elem.scrollHeight,
  19.  
  20. //scroll position of content & padding
  21. left: elem.scrollLeft,
  22. top: elem.scrollTop
  23. };
  24.  
  25. //position of element from the top-left corner of the document
  26. var tmp = elem;
  27. this.left = this.top = 0;
  28. while(tmp.offsetParent)
  29. {
  30. this.left += tmp.offsetLeft;
  31. this.top += tmp.offsetTop;
  32. tmp = tmp.offsetParent;
  33. }
  34. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.