How to display different banners for web/mobile


Adsense’s flex box has made it really simple to put in a piece of code which adapts to the size of available space. I had a situation where I wanted to put my own banners in and then realised I didn’t have the code to change the banner depending on the screen size. What I wanted was a dynamic ad block that displayed different ads depending on the width of the browser window so it wouldn’t mess up the mobile responsive version of the website.

The following is a simple piece of javascript which will display one 300×100 banner if the screen is less than 800px wide (mobiles) and a full 728×90 banner if the screen is more than 800px wide.

var docWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
if (docWidth >= 800) {
document.write(`<a href=”” ><img src=””></a>`);
} else {
document.write(`<a href=”” ><img src=””></a>`);

Notice the use of backticks “, this is ES6 Javascript which makes multi-line addition and variable insertions much easier.

The reason I wanted to change the banners was because for some reason Adsense earnings for a gambling related site I owned were ridiculously low. <£1 eCPM. I’m not sure why, perhaps a bad quality score or just Adsense isn’t effective for the vertical. Anyway I changed the links out to SkyBet Affiliate Hub and Ladbrokes Partners and am expecting 10x the eCPM’s in this niche.



Please enter your comment!
Please enter your name here