How can I dynamically change the HTML content of a Leaflet popup using JavaScript?
I have text in the popup that I want to change when it's clicked:
map_layer = L.geoJSON(countries, {
onEachFeature: this.country_clicked
}).addTo(this.map);
...
country_clicked = (country, layer) => {
// I spread the popup's HTML over multiple lines for readability:
layer.bindPopup("<p id='hide' onclick='show_hide()'>
Click me
</p>
<script>
function show_hide() {
document.getElementById('hide').innerHTML = 'New text...';
}
</script>"
);
}
The plain HTML part of the popup works fine, but when I click the paragraph text, my Angular throws an error:
Uncaught ReferenceError: show_hide is not defined
onclick map.component.css:1
I've seen this post but their solution makes the function run when the layer is clicked, not the popup content.
Is there a way for me to modify the popup HTML with JavaScript?
Edit, full Angular code:
map.component.ts:
export class MapComponent implements OnInit
{
init_map()
{
this.map = L.map("map", { ... });
this.map_layer = L.geoJSON(this.countries, {
onEachFeature: this.country_clicked
}).addTo(this.map);
}
...
country_clicked(country, layer)
{
layer.bindPopup('<p id="hide" onclick="show_hide(this, \'New text ...\')">
Click me
</p>');
}
show_hide(element, txt)
{
element.innerHTML = txt;
}
}
But this still throws Uncaught ReferenceError: show_hide is not defined
error.
I've tried putting the show_hide()
function everywhere and it still can't be found by the popup:
- Out of the
Map
class - Within the
Map
class - Within the
country_clicked
function
<script>
s and stuff like rewriting the definition of a function in a given scope.