Select to view content in your preferred language

How to addEventListener to a button in popup content of ArcGIS API for JS

2963
2
04-18-2022 10:29 AM
NoorMaria
New Contributor

I have created a custom popup with the popupTemplate function with ArcGIS JS API 4.x

And i add a button in popup content by html.

but i can not addEventListener to a button in popup.

here is the way i am try to do now: ((the full code is here:https://codepen.io/llllllllc/pen/mdpabGwmaterial))

  1. return html to create button in popup content
const popupTemplate = {
                // autocasts as new PopupTemplate()
                title: "Population in {NAME}",
                content: populationChange,
                };

                layer.popupTemplate = popupTemplate;

                function populationChange(feature) 
                {
                    const div = document.createElement("div");
                    div.innerHTML =
                        "<input type='button' id='btn' value='CLICK'>";
                    return div;
                }
  1. watch content change
view.popup.watch("content", (newValue, oldValue, propertyName, target) => {......});

3.querySelector("#btn") then addEventListener but it fail ,and console.log(btn) show btn is null

const btn = document.querySelector("#btn");
console.log(btn)
btn.addEventListener(
    "click",
    function () {
        lert("HELLO WORLD!");
    },
   false
);a

 F8v79.png

 

0 Kudos
2 Replies
ReneRubalcava
Honored Contributor

Here is a sample adding a button to the popup content.

https://codepen.io/odoe/pen/abEPGxR?editors=1000

You can either reuse the button you create, or be sure to remove the event listener if you don't

This is using the CustomContent of the PopupTemplate

https://developers.arcgis.com/javascript/latest/api-reference/esri-popup-content-CustomContent.html

0 Kudos
sarahjones4
Emerging Contributor

Along similar lines.

 

        function populationChange(feature) {
          const div = document.createElement("div");
          const btn = document.createElement("button")
          btn.innerHTML = 'Click Me'
          btn.onclick = function(props) {
            alert('hello world.')
          }
          return div.appendChild(btn)
        }

 

0 Kudos