Saturday, October 13, 2012

Adsense - Responsive Ads using a Javascript interface

Adsense - Responsive Ads with a Javascript interface

How to make responsive ads using Javascript

So, the idea is check the user screen size and then based on that value show up the ads.

In my case I have the following set:
  • Desktop
    • Leaderboard (728x90)

  • Portrait tablet to landscape and desktop
    • Banner (468x60)

  • Landscape phone to portrait tablet
    • Banner (468x60)

  • Landscape phones and down
    • Half Banner (234x60)


See the source code example:

 <script type="text/javascript">  
       google_ad_client = "ca-pub-XXXXXX";  
       google_ad_slot = "";  
       if(window.innerWidth >= 800) {  
        //visible-desktop  
        //Medium Rectangle  
        google_ad_slot = "xxxxxxx";  
        google_ad_width = 300;  
        google_ad_height = 250;  
       }  
       else if((window.innerWidth > 480)&&(window.innerWidth < 800)) {  
        //visible-tablet  
        //Square  
        google_ad_slot = "xxxxxxx";  
        google_ad_width = 250;  
        google_ad_height = 250;  
       }  
       else if(window.innerWidth <= 480) {  
        //visible-phone  
        //Large Rectangle  
        google_ad_slot = "xxxxxxx";  
        google_ad_width = 336;  
        google_ad_height = 280;  
       }  
       if(google_ad_slot != "")  
        document.write('1: <scr'+'ipt type=\"text/javascript\" src=\"http://pagead2.googlesyndication.com/pagead/show_ads.js\"></scri'+'pt>');  
       </script>  

Are you using Twitter Bootstrap? If so, you can make the same thing quite easier. Take a look!