Dynamic Ads







Explanation and sample code

You may want to serve different ad banners below a Riddle depending on the screen size. The example above loads a 728x90 banner, if the screensize is bigger than 728px and a 300x250 banner if the screensize is below that.
As the height of these 2 ad units differs greatly, you need to tell Riddle to re-size 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.

Steps to reproduce this example:

1. Remove this from the Riddle iFrame embed code:

				style="margin:0 auto;
                max-width:100%;
                width:640px;"
				

2. Embed the Riddle on your page.

Wrap the embed code into a 100% width container to re-create the example as shown above.

3. Create the ad iframe which you will then use in your Riddle as a footer ad.

Create a new file with this content:

<!DOCTYPE html>
<html>
<head>
    <title>Responsive Image</title>
    <style>
        #imageContainer {
            display: flex;
            justify-content: center;
        }
    </style>
</head>
<body>
    <div id="imageContainer">
        <img id="responsiveImage" src="">
    </div>
    <script src="responsiveImage.js"></script>
</body>
    
<script>
            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>

4. Create a new responsiveimage.js file

This file dynamically loads the ads based on the screensize. Here is the full code needed for that:

				window.addEventListener("load", (event) => {
	var img = document.getElementById('responsiveImage');
	console.log("innerwith: ", window.innerWidth)
    function setImgSrc() {
		
        if (window.innerWidth <= 727) {
            img.src = '/img/300x250.png';
        } else {
            img.src = '/img/728x90.png';
        }
    }
    setImgSrc();  // Call once at start to set the image initially
    window.onresize = setImgSrc;  // Call whenever the window is resized
});