1

I'm trying to make a marker popup in Leaflet (1.3.1) that:

  • Appears on mouseover ("hover")
  • Disappears on mouseout
  • Persists (stays open) on click

Here's what I have so far:

var marker1 = L.marker([51.505, -0.09]).addTo(mymap)
  .bindPopup("<b>Hello world!</b><br />I am a popup.");

marker1.on('mouseover', function (e) {
  this.openPopup();
});
marker1.on('mouseout', function (e) {
  this.closePopup();
});
marker1.on('click', function (e) {
  this.openPopup();
  //disable mouseout behavior here?
});

Plunker: https://embed.plnkr.co/393lgE49Ndqsj7O6dg19/

animated GIF screen capture demonstrating the problem

Mouseover and mouseout work as expected. When I click on the marker, the popup briefly disappears before reappearing. When I mouseout, the marker disappears.

I'd like it if the popup didn't briefly disappear when I click on it, and instead just stayed open until the user clicks the close 'x' button or clicks somewhere else on the map.

2

It could be done like this, but I'm pretty sure it's not the best way because it only works for marker1. Anyway, it's a start.

var marker1 = L.marker([51.505, -0.09]).addTo(mymap)
    .bindPopup("<b>Hello world!</b><br />I am a popup.");

let isClicked = false

marker1.on({
    mouseover: function() {
        if(!isClicked) {
            this.openPopup()
        }
    },
    mouseout: function() { 
        if(!isClicked) {
            this.closePopup()
        }
    },
    click: function() {
        isClicked = true
        this.openPopup()
    }
})

mymap.on ({
    click: function() {
        isClicked = false
    },
    popupclose: function () {
        isClicked = false
    }
})
4

I believe this issue is due to the fact that leaflet automatically closes popups on click. So, on click, it closes and then re-opens.

There is an option on the map for this: http://leafletjs.com/reference-1.3.0.html#map-closepopuponclick

Unfortunately it seems to be not working as of this post, see: https://github.com/Leaflet/Leaflet/issues/4189

There is also an option on the popup itself, which I could not get to work. http://leafletjs.com/reference-1.3.0.html#popup-closeonclick

Hopefully this can send you towards a solution.

UPDATE: You can try combining the above options and creating your popup differently.

const popup = L.popup(); marker1.bindPopup(popup);

  • I think you're right; I can't seem to get any of the closePopupOnClick options to work. :\ – MattSidor Feb 19 '18 at 4:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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