Richard Richard - 5 months ago 31
jQuery Question

Add a click event to an element rendered dynamically from Mustache?

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/

Answer

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.