2

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.

MattSidor
  • 141
  • 1
  • 1
  • 6

2 Answers2

5

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

jmfolds
  • 313
  • 1
  • 10
4

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
    }
})
Rodrigo Mota
  • 110
  • 7