How to handle Mapbox GL JS popup click events with custom HTML

1 week ago 10
ARTICLE AD BOX

Mapbox popups are added to the page only when they open, so normal click listeners won’t work directly.

Best and Clean Way

Listen for clicks on the document and catch popup buttons when they appear.

document.addEventListener("click", (e) => { if (e.target.classList.contains("popup-btn")) { console.log("Popup button clicked"); } }); popup.setHTML(`<button class="popup-btn">Click</button>`);

Quick and Simple

Inline click (okay for small demos):

popup.setHTML(`<button onclick="alert('Clicked')">Click</button>`);

For Bigger or Complex UI

Create the popup with real DOM and attach events normally:

const el = document.createElement("div"); el.innerHTML = `<button id="btn">Click</button>`; el.querySelector("#btn").addEventListener("click", () => { alert("Clicked"); }); popup.setDOMContent(el);

Final Tip

For simple popups, use event delegation.

For interactive popups, use setDOMContent().

Read Entire Article