Leaflet: how to add click event listener to popup?

14,166

Solution 1

Found final workaround! It works:

Here is my updated code:

for (var i = 0; i < users.length; i++) {
    (function (user) {
        var marker = L.marker([users[i].lat, users[i].lon], {icon: iconOff})
            .on('mouseover', function() { this.setIcon(iconOn); })
            .on('mouseout', function() { this.setIcon(iconOff); })
            .addTo(map);

        var myPopup = L.DomUtil.create('div', 'infoWindow');
        myPopup.innerHTML = "<div id='info'><p id='title'>" + users[i].title + "</p><p>" + users[i].addr + "</p></div>";

            marker.bindPopup(myPopup);

        $('#info', myPopup).on('click', function() {
            $("#userTitle").html(users[i].title).html();
            $("#userAddr").html(users[i].addr).html();
            $("#userDesc").html(users[i].desc).html();

            $("#userDetails").modal("show");
        });
    })(users[i]);
}

As you can see i create the content of the popup using L.DomUtil (DOM element) instead of L.Popup (string) for creating content for the popup. In addition, in my case i added an anonymous function to handle data from JSON.

I got inspired by this link

Solution 2

Another possible way is to bind the event listener to the elements of the popup.

For example:

    var popup = L.popup({offset   : new L.Point(0,-24), 
                         className: 'some-class'})
                             .setLatLng(latlng)
                             .setContent(content)
                             .openOn(map);

    // can access popup._container or popup.contentNode
    $(popup._closeButton).one('click', function(e){
        //do something
    });
Share:
14,166

Related videos on Youtube

smartmouse
Author by

smartmouse

Considerable experience in web applications development, both as front-end developer and as CMS webmaster. Bitcoin and blockchain enthusiast as writer, speaker and developer of personal projects. An effective communicator with good leadership and analytical skills. Seeking new challenges and responsibilities to progress career. Spare time is for reading news, traveling and working on new ideas...

Updated on June 04, 2022

Comments

  • smartmouse
    smartmouse almost 2 years

    i'm using Leaflet library for the first time and i would add a click event listener on popup for every marker.

    Here is my code:

    for (var i = 0; i < users.length; i++) {
      var marker = L.marker([users[i].lat, users[i].lon], {icon: iconOff})
        .on('mouseover', function() { this.setIcon(iconOn); })
        .on('mouseout', function() { this.setIcon(iconOff); })
        .addTo(map);
    
      var myPopup = L.popup()
        .setContent("<div id='info'><p id='title'>" + users[i].title + "</p><p>" + users[i].addr + "</p></div>");
    
      marker.bindPopup(myPopup).openPopup();
    }
    

    I tried to attach a MouseEvent to popup, doing this before binding myPopup to marker:

    myPopup.on('click', function() { alert("Hello"); })
    

    But it doesn't work. I also tried to add this following jQuery code (i'm working on Bootstrap and clicking on popup has to show a modal):

      $("#info").click(function() {
        $("#userTitle").html(users[i].title).html();
        $("#userAddr").html(users[i].addr).html();
        $("#userDesc").html(users[i].desc).html();
    
        $("#userDetails").modal("show");
      });
    

    Here is the HTML code:

    <?php
      $title = "Map";
      $scriptsH = array('http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js', 'js/showmap.js');
      require_once('header.php');
    ?>
        <div class="cointainer">
            <div id="map-canvas">
            </div>
      </div>
      <div class="modal fade" id="userDetails" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="userTitle"></h4>
          </div>
          <div class="modal-body">
              <p id="userDesc"></p>
              <p id="userAddr"></p>
          <div class="modal-footer">
            <button type="button" class="btn btn-primary" data-dismiss="modal">Chiudi</button>
        </div>
          </div>
        </div>
      </div>
    <?php
      require_once('footer.php');
    ?>
    

    But it just works on first marker with popup already opened.

    Do you know any workaround or just the right way to do that?

    • Akshay Khandelwal
      Akshay Khandelwal almost 9 years
      Can we see the exact code?
    • Vigneswaran Marimuthu
      Vigneswaran Marimuthu almost 9 years
      i don't think Leaflet Popup supports any events
    • smartmouse
      smartmouse almost 9 years
      @akshay: what do you need?
    • Akshay Khandelwal
      Akshay Khandelwal almost 9 years
      I need to see your html code along with the javascript that you have already posted here
    • smartmouse
      smartmouse almost 9 years
      @AkshayKhandelwal: I edited my question, please have a look.
    • smartmouse
      smartmouse almost 9 years
      @VigneswaranMarimuthu: any workaround?
    • Vigneswaran Marimuthu
      Vigneswaran Marimuthu almost 9 years
      @smartmouse Might be a dirty hack. Add inline onclick listener to the popup content (root element).
    • smartmouse
      smartmouse almost 9 years
      How? Can you show what you mean?
    • smartmouse
      smartmouse almost 9 years
      I tried this code: document.getElementById("info").addEventListener("click", function() { console.log("hello"); }); but its behavior is the same of $("#info").click()