[GIS] Leaflet javascript in popup

javascriptleafletpopup

Can JavaScript be included in a leaflet popup?

We have modified this example

To this :-

var this_marker = L.marker([51.5, -0.09]).addTo(mymap).bindPopup(
 '<div style="color: red">Hello<br>world<script>console.log("testing");
  </script></div>').openPopup();

This gives an error.

In our application we see the correctly formed HTML with script tags but the JavaScript does not run.

Best Answer

Your code above works great without the <script> tag once its removed, like so:

var this_marker = L.marker([51.5, -0.09]).addTo(mymap).bindPopup
('<div style="color: red">Hello<br>world</div>').openPopup();

If you are trying to add in additional JavaScript functionality to the popup when its open you could use a selector such as:

mymap.on('popupopen', function() {
    console.log(testing);    
});