I am trying to add click handler dynamicaly but it doesn't work. Here is my code:
function refreshSidebar(){
if (mapMode=="normal") { features=allFeatures.getSource().getFeatures()}
else if (mapMode=="filtered") {features=filteredFeatures.getSource().getFeatures()}
$("#list").html("");
html="<ul>"
for (i=0;i<features.length;i++)
{
if (typeof features[i].description!="undefined"){
html+="<li id=FEAT_"+features[i].id+">"+features[i].description+"</li>";
$("#FEAT_"+features[i].id).prop("onclick", null).off("click");
$("#FEAT_"+features[i].id).on('click', function()
{
map.getView().setCenter(features[i].geometryChangeKey_.target.getFlatCoordinates());
map.getView().setZoom(10)
})
}
What am I doing wrong?
The issue is that $("#FEAT_"+features[i].id)
will try to find an element with that selector in the DOM. Your HTML only exists in a string at that point and so that element cannot be found and the event listener will not be attached.
Instead of creating a string containing the HTML, you can create elements to which you can attach the event to. You can do this before the element is part of the DOM and attach the element to the DOM afterwards.
$("#list").html("");
const list = $("<ul></ul>");
for (let i = 0; i < 5; i++) {
const listItem = $("<li id=FEAT_" + i + ">List item " + i + "</li>");
listItem.click(function() {
console.log('List item clicked', this.id);
});
list.append(listItem);
}
$("#list").append(list);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="list">
</div>