Friday, April 4, 2014

[JavaScript][Solved] Display different google adsense ad base on different browser width

This is the solution and you can simplily copy the code and change the text in red to your 's adsense information to make it work:
<script type="text/javascript">
    google_ad_client = "ca-pub-4664799911805302";
    width = document.documentElement.clientWidth;
    google_ad_slot = "9764084514"; // <-Default show this ad    google_ad_width = 320;
    google_ad_height = 250;
        if (width > 500) {
        google_ad_slot = "9764084514"; // <-If the browser width is smaller than 500px , show this as with 300x250px        google_ad_width = 300;
        google_ad_height = 250;      
    }
    if (width > 800) {
        google_ad_slot = "4556985713";// <-If the browser width is bigger than 800px , show this ad with 728x90px        google_ad_width = 728;
       google_ad_height = 90;
    }
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>

You can test it by re-sizing the browser windows. however, if you re-size the browser window after the ad displayed, you need refresh the page to load the ad with another size.

Reference:
http://stackoverflow.com/questions/10066553/displaying-a-different-adsense-ad-based-on-browser-width
http://ryanunderdown.com/adsense/responsive-ads-with-adsense.php

No comments :

Post a Comment