Dynamic ad size in Riddle
You may want to serve different ad banners below a Riddle depending on the screen size. The example below loads a 728x90 banner, if the screen size is bigger than 728px and a 300x250 banner if the screen size is below that. As the height of these two ad units greatly differs, you need to tell Riddle to resize the space assigned to the banner ad. This happens with a small script that pushes the height parameter into the Riddle iframe. Lastly, you need to slightly alter the Riddle embed code and remove the parameters that set a fixed maximum width for this example to work.
Code of the ad iframe
This is the code of the iframe that is loaded in the monetization ad slot below the Riddle.
With this function you can send the current height of the iframe to the Riddle. This is required because the iframe can only be resized by its parent website.
function sendMessage() {
window.parent.postMessage({
"ad-iframe-bottom": document.body.offsetHeight,
}, "*");
}
Complete code
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Resize</title>
<style>
#imageContainer {
display: flex;
justify-content: center;
}
body {
margin: 0;
}
</style>
</head>
<body>
<div id="imageContainer">
<img id="responsiveImage" src="">
</div>
</body>
<script>
var img = document.getElementById('responsiveImage');
function setImgSrc() {
if (window.innerWidth <= 727) {
img.src = '/img/300x250.png';
} else {
img.src = '/img/728x90.png';
}
}
// Call once at start to set the image initially.
setImgSrc();
// Call whenever the window is resized.
window.onresize = setImgSrc;
function sendMessage() {
window.parent.postMessage({
"ad-iframe-bottom": document.body.offsetHeight,
}, "*");
}
(function () {
sendMessage()
var height = document.body.offsetHeight;
setInterval(function () {
if (height != document.body.offsetHeight) {
sendMessage()
height = document.body.offsetHeight;
}
}, 100)
})();
</script>
</html>