Ant Bentinck Ant Bentinck - 29 days ago 19
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 A-Ads.com Unit
if (width >= 768) {
<iframe src="#" </iframe>
} else if ((width < 799) && (width >= 480)) {
<iframe src="#" </iframe>
} else {
<iframe src="#" </iframe>
}
</script>


Ive tried this also:

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

Answer

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 :

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

FIDDLE: http://jsfiddle.net/yLjzn/1/