Richard Richard - 1 year ago 96
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:

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download