iframe dynamic resize


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

JavaScript code to facilitate dynamic re-sizing of an iframe at the same time as the browser window is re-sized, as well as making sure that the frame scales proportionally to its width and height.


Copy this code and paste it in your HTML
  1. <script type="text/javascript">
  2.  
  3. $.noConflict();
  4. function adjustIframes()
  5. {
  6. $('iframe').each(function(){
  7. var
  8. $this = $(this),
  9. proportion = $this.data( 'proportion' ),
  10. w = $this.attr('width'),
  11. actual_w = $this.width();
  12. if ( ! proportion )
  13. {
  14. proportion = $this.attr('height') / w;
  15. $this.data( 'proportion', proportion );
  16. }
  17. if ( actual_w != w )
  18. {
  19. var h = Math.round( actual_w * proportion );
  20.  
  21. if (!isNaN(h)) {
  22. if (console && console.log) console.log("Resizing iframe to height: " + h);
  23. $this.css( 'height', h + 'px' );
  24.  
  25. if ($this.get(0).contentWindow.postMessage) {
  26. $this.get(0).contentWindow.postMessage('resize', 'your website here');
  27. }
  28. }
  29. }
  30. });
  31. }
  32. $(window).on('resize load',adjustIframes);
  33. });
  34. </script>

URL: javascript, jquery, iframe

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.