JavaScript Iframe Auto Resize


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

Given an iframe element and a header element, make the iframe just high enough to fit in the browser window. On window resize, readjust. Keep a minimum height for the iframe.


Copy this code and paste it in your HTML
  1. function autoSizeIframeHeight(iframe, header, minHeight) {
  2. minHeight = minHeight || 300;
  3. function getViewportHeight() {
  4. var h = document.documentElement.clientHeight;
  5. return document.compatMode === "CSS1Compat" && h || document.body.clientHeight || h;
  6. }
  7. function getHeaderHeight() {
  8. return parseFloat(getComputedStyle(header,'height'));
  9. }
  10. function getComputedStyle(el, cssprop){
  11. if (el.currentStyle) { // IE
  12. return el.currentStyle[cssprop];
  13. }
  14. else if (document.defaultView && document.defaultView.getComputedStyle) {
  15. return document.defaultView.getComputedStyle(el, "")[cssprop];
  16. }
  17. else {
  18. return el.style[cssprop];
  19. }
  20. }
  21. function setIframeHeight() {
  22. var toHeight = getViewportHeight() - getHeaderHeight();
  23. iframe.height = Math.max(toHeight, minHeight);
  24. body.style.overflowY = toHeight < minHeight ? 'auto' : 'hidden';
  25. }
  26. var body = document.body || document.getElementsByTagName('body')[0];
  27. setIframeHeight();
  28. if (window.addEventListener) {
  29. window.addEventListener('resize', setIframeHeight, false);
  30. }
  31. else if (window.attachEvent) {
  32. window.attachEvent('onresize', setIframeHeight);
  33. }
  34. }
  35. // example usage:
  36. // autoSizeIframeHeight(document.getElementById('MyFrame'), document.getElementsByTagName('header')[0], 300);

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.