Jul 28, 2013

How to Add Responsive Google Ad Code

Posted Jul 28, 2013
Many asked before if it's legal to change the ad size through javascript, now it's official, Google allows modification of its ad sense code for responsive design.  You won't be breaking any terms and conditions when you do this.

Do note that the adsense javascript code below is not really responsive in a sense that when you resize the browser, the ads change size dynamically; no it doesn't do that. It only checks the window size at start and set the appropriate ad size. You have to refresh the page after resizing the browser to see the ad size change.

The code:
<script type="text/javascript">
    google_ad_client = "your publisher id"; //change
    width = document.documentElement.clientWidth;
    google_ad_slot = "111"; //change
    google_ad_width = 320;
    google_ad_height = 50;
        if (width > 500) {
        google_ad_slot = "111"; //change
        google_ad_width = 468;
        google_ad_height = 60;
    }
    if (width > 800) {
        google_ad_slot = "111"; //change
        google_ad_width = 728;
       google_ad_height = 90;
    }

</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>

At least it's getting there, maybe soon we'll see a truly responsive ad.

No comments:

Post a Comment