Ant Bentinck Ant Bentinck - 1 year ago 123
Javascript Question

Load Iframe based on screen width

Hey just looking for shunt in the right direction.

I have 3 Iframes which I want to be displayed at certain screen sizes I know i'm way off here I have tried a few things. any help would be appreciated.

<script type="text/javascript">
// Responsive Unit
if (width >= 768) {
<iframe src="#" </iframe>
} else if ((width < 799) && (width >= 480)) {
<iframe src="#" </iframe>
} else {
<iframe src="#" </iframe>

Ive tried this also:

<script type="text/javascript"
$(function () {
var width = $(window).width();
if (width <= 600) {
$('<iframe data-aa="4970" src="//" scrolling="no" style="width:468px; height:60px; border:0px; padding:0;overflow:hidden" allowtransparency="true"></iframe>').appendTo('body');
} else {
$('<iframe data-aa="14739" src="//" scrolling="no" style="width:728px; height:90px; border:0px; padding:0;overflow:hidden" allowtransparency="true"></iframe>').appendTo('body');

Answer Source

A way to detect in all browsers is using the property window.screen.availWidth (detects total width of screen, not window) or the one you already tried using JQuery $(window).width()(detects current width of the window as seen in the fiddle attached in the end).

Since resize is not an option for you, you could add your iframes to a div after the width check, in this example I insert DOM content in a div with id content using html() method :

  if (window.screen.availWidth >= 768) { 
    $('#content').html('<iframe src="" id="frame1" style="display:block"></iframe>');
  } else if ((window.screen.availWidth < 799) && (window.screen.availWidth >= 480)) {
    $('#content').html('<iframe src="" id="frame2" style="display:block"></iframe>');
  } else { 
    $('#content').html('<iframe src="" id="frame3" style="display:block"></iframe>');
      <div id="content"></div>


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download