Richard Richard - 3 months ago 13
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">{{}}</p>
<input type="submit" id="clickme" value="clickme" />
<div class="cartodb-popup-tip-container"></div>

Should this affect my ability to add an event dynamically?

Link to a JSFiddle showing the problem in full:


Not too familiar with Carto myself, but it seems to work fine once you wait for the element to exist.

// 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.