I had a situation where I wanted to use different ad banners depending on the screen size of the visitor. To display different banners for mobile and desktop traffic.
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.
<div id="banner-container"></div>
<script>
var docWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
if (docWidth >= 800) {
document.getElementById('banner-container').innerHTML = `<a href="https://affiliatelink1.com" ><img src="banner1.jpg"></a>`;
} else {
document.getElementById('banner-container').innerHTML = `<a href="https://affiliatelink2.com" ><img src="banner2.jpg"></a>`;
}
</script>
Notice the use of backticks “, this is ES6 Javascript which makes multi-line addition and variable insertions much easier. Note that this wouldn’t be compatible with really old browsers such as Internet Explorer.
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.