[GIS] Dynamic content in infoWindow

cartoinfowindow

I am trying to add some dynamic content to my infoWindow. The following code writes the string 'bar' to the element. However this works for the infoWindow of some points, but not for others (content is in variable, but not shown in the popup) in Firefox. Does not seem to work in Chrome at all.
Any suggestions on how to do this?
Edit: Surprisingly it works if an alert() popup is opened before the infoWindow.

 <script type="infowindow/html" id="infowindow_template">
  <div class="cartodb-popup">
    <a href="#close" class="cartodb-popup-close-button close">x</a>
     <div class="cartodb-popup-content-wrapper">
       <div class="cartodb-popup-content" id="foo">
         <img style="width: 100%" src="http://someurl.com/pic.png">
         <div id="foo"> </div> 
       </div>
     </div>
     <div class="cartodb-popup-tip-container"></div>
  </div>
</script>

<script src="http://libs.cartodb.com/cartodb.js/v3/3.11/cartodb.js"></script>



<script>
  function main() {
    var map = L.map('map', { 
      zoomControl: false,
      center: [0, 0],
      zoom: 5
    });

    L.tileLayer('http://{s}.tile..../{z}/{x}/{y}.png', {    
       attribution: '<a href=http://...> ...</a>'
    }).addTo(map);

    cartodb.createLayer(map, 'http://.../viz.json')
     .addTo(map)
     .on('done', function(layer) {

       var sublayer = layer.getSubLayer(0);

       sublayer.infowindow.set('template', $('#infowindow_template').html());

       sublayer.on('featureClick', function(e, pos, latlng, data) {
       //alert(pos);
        bar = httpGet('https://api...' + pos);
        document.getElementById("foo").innerHTML = bar;

        });

      }).on('error', function() {
        console.log("some error occurred");
      });
  }

  function httpGet(theUrl){
    // do an API call to do stuff with the position and return a result
    return result;
    }


  window.onload = main;
</script>

Best Answer

You may want to define the content of your infowindow template in your js code, and your infowindow template would look like this

<script type="infowindow/html" id="infowindow_template">
  <div class="cartodb-popup">
    <a href="#close" class="cartodb-popup-close-button close">x</a>
     <div class="cartodb-popup-content-wrapper">
       <%= infowindow_content() %>
     </div>
     <div class="cartodb-popup-tip-container"></div>
  </div>
</script>

Then, your js code:

function infowindow_content()
{
    // Do something to get your dynamic content here
    //var dyncontent = ...

    var html = "<div class='cartodb-popup-content' id='foo'><img style='width: 100%' src='http://someurl.com/pic.png'><div id='foo'>" + dyncontent + "</div></div>";

    return html;
}

Check my response here

Related Question