[GIS] Show popup on marker hover / mouseover, hide on mouseout, and keep open on click

htmljavascriptleafletmapbox

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.

Best Answer

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);