How to make a element in .bindpopup accessible for external functions in leaflet?

Viewed 258

I have a function that feeds variables to a Popup, which is working so far. Now I inserted a button in this Popup and want some function to run when clicked on this, but the the object is not accessible for my external function. How can I rewrite this function, to access the single elements more easy?

marker:

var marker      = L.marker([data[i].lat, data[i].lng], {icon: greenIcon}).addTo(map);
marker.bindPopup(id + "<br>" + species + "<br>" + diameter + "<br>" + quality + "<br>" + damage + "<br>" + notes + "<br>" + "<br>" +
'<input type="submit" id = "delete" name="action" data-value = " + id + " value="Delete" method = "post"/>');
        

function:

<script type="text/javascript">
    $(function(){
        $('#delete').click(function(d){
            
        alert("deleted")
    });
});
</script>
2 Answers

You have to add the listener after the Popup is opened:

marker.on('popupopen',function(e){
    $('#delete').click(function(d){ 
        alert("deleted")
    });
}

As you have figured out, what you provide to bindPopup in your code is just an HTML string that you cannot directly use to attach an event listener to.

You have several possible solutions for this:

  • build an HTML Element to pass to bindPopup instead of a String, so that you can manipulate it as an object

  • defer the attachment of your listener to after the popup is open, hence the HTML string is converted to a DOM element on the page

  • use event delegation to attach your listener to a parent element instead, which already exists in DOM, but filtering events to target your future button

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

With jQuery this could be like:

$("body").on("click", "#delete", myListenerFunction);
Related