0

I am trying to add a click event to an element that is added dynamically to the page after document load, but it isn't working, though this seems to be a well-known problem with a clear answer. This is my code:

  $('body').on('click', "#clickme", function() {
    alert('clicked!', $('#cartodb_id').text());
  });

The complicating factor may be that the element is inside a Mustache template that itself gets rendered dynamically into the page, by CartoDB.js:

<div id="map"></div>
<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">
        <h4>cartodb_id: </h4>
        <p id="cartodb_id">{{content.data.cartodb_id}}</p>
        <input type="submit" id="clickme" value="clickme" />
      </div>
    </div>
    <div class="cartodb-popup-tip-container"></div>
  </div>
</script>

Should this affect my ability to add an event dynamically?

Link to a JSFiddle showing the problem in full: http://jsfiddle.net/8o12v2xs/9/

Community
  • 1
  • 1
Richard
  • 62,943
  • 126
  • 334
  • 542

1 Answers1

1

Not too familiar with Carto myself, but it seems to work fine once you wait for the element to exist. http://jsfiddle.net/8o12v2xs/10/

// register events once it's available
sublayer.on('featureClick', function(e, latlng, pos, data) {
    $('#clickme').on('click', function() {
        alert('clicked!', $('#cartodb_id').text());
    })
});

Put that underneath the initialization like in the above Fiddle.

Matt Kenefick
  • 1,173
  • 1
  • 13
  • 22
  • Yes! Thank you so much. If you have time, could you explain exactly why that works? Is it because the Mustache element only gets rendered to the page when `featureClick` occurs? – Richard Jun 29 '16 at 22:35
  • When you click on a dot, the map is replacing several elements and so they won't exist until a click occurs. Click a dot, open the inspector and select the window, then watch how it rebuilds when you click a different dot. – Matt Kenefick Jul 01 '16 at 05:33