0

I have a Leaflet map with leaflet-control-geocoder plugin for searching feature. I'm trying to customize popup with some javascript. The issue is, that javascript works only once on first popup opening and after each close/open popup action appears more elements in popup block and JavaScript doesn't work. I tried to use

map.on("popupclose", function (e) {}) 

and some how to remove/delete cretead items, but didn't work for me.

map.on("popupopen", function (e) {
          let button =
            "<span class='popup-btn-wrapper'><button class='popup-btn'>Check availibility</button></span>"; //define button
          let section = "<div class='popup-text'>&nbsp</div>";
          let content = e.popup.getContent(); //get location name "London"

          e.popup.setContent(content + section + button); // add button to PopUp

          let wrapper = document.getElementsByClassName(
            "leaflet-popup-content-wrapper"
          )[0];
          let targetDiv = document.getElementsByClassName("popup-text")[0];
          let btnWrapper =
            document.getElementsByClassName("popup-btn-wrapper")[0];
          let btn = document.getElementsByClassName("popup-btn")[0];

          L.DomEvent.on(btn, "click", () => {
            console.log("clicked");
            if (targetDiv.style.display === "none") {
              targetDiv.style.display = "block";
              wrapper.style.height = "150px";
              btnWrapper.style.top = "70%";
            } else {
              targetDiv.style.display = "none";
              wrapper.style.height = null;
              btnWrapper.style.top = "60%";
            }
          });
        });
//Search
L.Control.geocoder({
  collapsed: true
  position: "topleft"
  text: "Search"}).addTo(map);
0

1 Answer 1

0

Content of popup has to be modified only the first time it's opened after creation. To detect that, some custom popup property can be introduced (name must differ from existing properties), like initDone, which is set to true after first popup content modification.

Relevant part of the code could then look something like this:

map.on("popupopen", function (e) {
  if (e.popup.initDone) return;
  
  let e.popup.initDone = true;
  let button = "<span class='popup-btn-wrapper'><button class='popup-btn'>Check availibility</button></span>"; //define button
  let section = "<div class='popup-text'>&nbsp</div>";
  let content = e.popup.getContent(); //get location name "London"
  .
  .
  .
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.