608.620.5104 | info@tenforward.consulting

How to make a non-video iframe responsive, using JavaScript

Published June 2, 2022

The Challenge

We needed to embed an iframe for a third-party form on a client website. The form itself was responsive, in that at a certain width, form fields went from two columns to one column, which meant it wasn't a simple matter of just proportionally resizing the iframe container (the way we do with embedded videos). 

Desktop looked fine with an iframe container that had a height of 250px:

But mobile .... didn't:

The Solution

The only way we could figure out to have the iframe container be the right size at different screen widths was to actually load different iframe tags, using the same breakpoints in JavaScript as the form we were embedding used (in this case, 685px) via window.matchMedia:

HTML

<div class="js-iframe-container">
</div>


CoffeeScript

$(document).ready =>
  if window.matchMedia("(min-width: 685px)").matches
   	iframeHTML = "<script type='text/javascript' src='https://link-to-the-iframe.com&width=100%&height=350'>"
  else
   	iframeHTML = "<script type='text/javascript' src='https://https://link-to-the-iframe.com&width=100%&height=500'>"
      
  $(".js-iframe-container").html(iframeHTML)


Mobile 🎉


Author details

Hilary Stohs-Krause

Co-Owner and Senior Software Developer
@hilarysk