I'm looking to fit Google AdSense ads into a responsive design (specifically using Twitter Bootstrap).
The challenge is that with a responsive design the width of the container can change depending on the width of your browser window. While this is one of the major strengths for responsive design, it can be difficult to fit fixed-width content, like advertisements. For example, a given container may be 300px wide for users viewing the page with a browser at least 1200px wide. But in a 768px wide browser window, the same container might only be 180px wide.
I'm looking for JavaScript (jQuery?) solution to load the largest ad format that fits the width of the container.
Assume I have the following Ad Slots (ad formats):
name width x height slot_id
slot_180 180 x 160 1234567890
slot_250 250 x 250 2345678901
slot_300 300 x 250 3456789012
slot_336 336 x 280 4567890123
slot_728 728 x 90 5678901234
Here's the script that I need to include:
<script type="text/javascript"><!--
google_ad_client = "ca-ABCDEFGH";
google_ad_slot = "[###slot_id###]";
google_ad_width = [###width###];
google_ad_height = [###height###];
//--></script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>';
And here's some sample html:
<body>
<div class="row">
<div class="span3"><p>Lorem ipsum</p></div>
<div class="span3" id="adSlot1"><!-- [### INSERT AD 1 HERE ###] --></div>
<div class="span3"><p>Lorem ipsum</p></div>
<div class="span3"><p>Lorem ipsum</p></div>
</div>
<div class="row">
<div class="span4" id="adSlot2"><!-- [### INSERT AD 2 HERE ###] --></div>
<div class="span4"><p>Lorem ipsum</p></div>
<div class="span4" id="adSlot3"><!-- [### INSERT AD 3 HERE ###] --></div>
</div>
</body>
I'd like to show the largest ad slot that fits in the given container.
For example:
If #adSlot1 is 300px wide, let's show slot_300
(or rather the id: 3456789012
along with its width and height in the AdSense JavaScript).
Now let's say you view the page on another device and #adSlot1 is now 480px wide. Now let's use slot_336
. 1000px wide element? Use slot_728
. Get it?
Note that it's against Google's TOS to render all different slots and merely .show()
/ .hide()
depending on the width. Instead if the ad JavaScript is called, it must be visible on the page. (Imagine how this would screw up everyone's reports if hidden ads were counted as impressions!)
I'm also not so concerned with folks stretching and shrinking their browser window during a page view. But bonus points if there's a savvy answer to this. Until then, this can load once per page load.
What do you suggest is the best, most elegant way to accomplish this?