Change DFP ad position after loading dynamic content

834 views Asked by At

I need to insert a DFP ad (Medium Rectangle) in between some dynamic contents. The contents load via AJAX and later populated as below in .items.

<div class="items">
  <div>The DFP ad</div>
  <div>New content</div> 
  <div>New content</div> 
  <div>New content</div> 
  <div>New content</div> 
</div>

I need the ad to be displayed after third the dynamic content for example. Changing via JS (Jquery) causes erratic ad rendering, mostly just leaving the ad to be empty.

1

There are 1 answers

0
Oleg Kuralenko On

If I got the question correctly you just need to add an ad slot dynamically.

Here's a working example that dynamically creates ad slots: https://github.com/ffeast/gpt-tests/blob/master/dynamic_slots.html

And here it is live: https://jsfiddle.net/Lpqtrtgu/

This is the excerpt that creates a new ad slot and renders it:

    var slotId = 1;
        function addNewSlot() {
            // add a div containing the dynamic ad
            var label = document.createElement('h1');
            label.innerHTML = 'Dynamic slot #' + slotId;
            document.body.appendChild(label);
            var container = document.createElement('div');
            container.id = 'slot-' + slotId;
            document.body.appendChild(container);
            // dynamic slot creation
            googletag.cmd.push(function() {
                var slot = googletag.defineSlot('/46362926/test_slot1', [240, 400], container.id).addService(googletag.pubads());
                googletag.cmd.push(function() { googletag.display(container.id); googletag.pubads().refresh([slot]); });
            });
            slotId++;
        };

The official docs on how to handle such cases in DFP: https://support.google.com/dfp_premium/answer/4578089?hl=en