Dynamic Ad Unit Insertion and Displaying Different Ads Based on the User's Device
You can use this guide if you have two ad units of different sizes and want to display a specific banner based on your visitors' screen size.
- Firstly, you need to create ad units. If you haven't done it yet, you may follow the steps in our Helpdesk article
- After that, you need to insert a
div
block with the class "banner-iframe-selector" into your HTML, which will contain the ad units:
<div class="banner-iframe-selector">
<div class="banner-iframe" data-src="https://ad.aads.com/2166128?size=300x250" data-max-width="467"></div>
<div class="banner-iframe" data-src="https://ad.aads.com/1?size=728x90"></div>
</div>
- Finally, you should insert the script that will display the ad based on the user's screen size:
<script>
document.addEventListener('DOMContentLoaded', () => {
const addIframe = (src, width, height, aa) => {
const iframe = Object.assign(document.createElement('iframe'), {
src, width, height, frameBorder: 0
});
iframe.setAttribute('data-aa', aa);
return iframe;
};
const updateBanner = () => {
const bannerDivs = document.querySelectorAll('.banner-iframe-selector .banner-iframe');
bannerDivs.forEach(div => div.style.display = 'none');
for (const div of bannerDivs) {
const maxWidth = parseInt(div.getAttribute('data-max-width'));
const src = div.getAttribute('data-src');
const aaMatch = src?.match(/\/(\d+)\?/), sizeMatch = src?.match(/size=(\d+)x(\d+)/);
if (aaMatch && sizeMatch && (window.innerWidth <= maxWidth || !maxWidth)) {
const [_, aa] = aaMatch, [__, width, height] = sizeMatch;
div.innerHTML = '';
div.appendChild(addIframe(src, width, height, aa));
div.style.display = 'block';
break;
}
}
};
updateBanner();
window.addEventListener('resize', updateBanner);
});
</script>
- Done! Now you can test it on different devices!
Updated on: 08/10/2024
Thank you!