Unable to duplicate JS variable for prebid slot

95 views Asked by At

This code has to do with serving ads on my site. The top part is where each of the ad slots gets defined. Then I have a function that will load any individual ad. This function needs to pull the appropriate ad slot variable defined at the top, but it doesn't seem to work.

var slot1;
googletag.cmd.push(function () {
    slot1 = googletag.defineSlot('/50970423/ffn-hb-rect-1', [[300, 250]], 'div-1')
        .addService(googletag.pubads());
    googletag.pubads().disableInitialLoad();
    googletag.pubads().enableSingleRequest();
    googletag.enableServices();
});
var slot2;
googletag.cmd.push(function () {
    slot2 = googletag.defineSlot('/50970423/ffn-hb-rect-ex', [[300, 250]], 'div-2')
        .addService(googletag.pubads());
    googletag.pubads().disableInitialLoad();
    googletag.pubads().enableSingleRequest();
    googletag.enableServices();
});

function refreshBid(adUnitName) {
    if (adUnitName == '/50970423/ffn-hb-rect-1') {
        var slot_to_load = slot1;
    }
    else if (adUnitName == '/50970423/ffn-hb-rect-ex') {
        var slot_to_load = slot2;
    }


    pbjs.que.push(function () {
        pbjs.requestBids({
            timeout: PREBID_TIMEOUT,
            adUnitCodes: [adUnitName],
            bidsBackHandler: function () {
                pbjs.setTargetingForGPTAsync([adUnitName]);
                googletag.pubads().refresh([slot_to_load]);
            }
        });
    });

}

Thing is, if I change that line near the end to googletag.pubads().refresh([slot1]); it will work perfectly (of course this only works for the first ad slot since it's hardcoded, so it's not a solution to the problem). Any ideas? Thanks!

1

There are 1 answers

0
guyot On

You're defining the slot_to_load variable inside your if/else statement, so at that bottom line slot_to_load is undefined. Define the variable outside the if/else and then set its value within and your code will work:

function refreshBid(adUnitName) {
    var slot_to_load;
    if (adUnitName == '/50970423/ffn-hb-rect-1') {
        slot_to_load = slot1;
    }
    else if (adUnitName == '/50970423/ffn-hb-rect-ex') {
        slot_to_load = slot2;
    }


    pbjs.que.push(function () {
        pbjs.requestBids({
            timeout: PREBID_TIMEOUT,
            adUnitCodes: [adUnitName],
            bidsBackHandler: function () {
                pbjs.setTargetingForGPTAsync([adUnitName]);
                googletag.pubads().refresh([slot_to_load]);
            }
        });
    });

}