Search code examples
javascriptjquerynamespacesgoogle-publisher-tag

i++ passed from JavaScript for loop to jQuery(document).ready(function() { not working as dynamic index when iterating over the array


For my sins I am not a full-time JavaScript practitioner, but I am trying. Here is a simplified version of my attempted ad management namespace which uses the Google Publisher Tag API

slots is an array of GPT slots as returned by googletag.defineSlot(, set in the head which tries to target divs that only exist post-CMS HTML rendering by deferring it to jQuery.

How can I do this:

var i;
for (i=0;i<slots.length;i++) {
    jQuery(document).ready(function() { 
        jQuery('#ads').append('<div id="'+slots[i].getSlotElementId()+'"></div>');
    });
}

...with a dynamic i, because when I've been debugging it I've seen that I can't pass i like this, and can only pass a hard-coded index.

This works within the jQuery(document).ready(function() {:

console.log('adManager.all_devices.button.slots[3].getSlotElementId());

This causes undefined errors:

console.log('adManager.all_devices.button.slots[i].getSlotElementId());

I have been reading (honest) but I'm confused. In gentle-terms, what's going on here and how can I fix it?


Solution

  • You have a wrong construction. You need to attach ready listener once and then inside callback do your loop. As below:

      jQuery(document).ready(function() {
        for (var i=0;i<slots.length;i++) {
            jQuery('#ads').append('<div id="'+slots[i].getSlotElementId()+'"></div>');
        }
      });