eug100
eug100

Reputation: 189

Leaflet: click event not always fired when a popup is used

I have a layer with onclick handler:

countriesLayer = L.geoJson(ct, {
    style: myStyle,
    onEachFeature: onEachFeature
})

function onEachFeature(feature, layer) {
    var center = setLabelCenter(layer);
    feature.center = [center.lng, center.lat];
    layer.on({
        click: onFeatureClick,
        mouseover: showMapTip,
    });
}

Also I have a popup for mouse over:

function showMapTip(e) {
    var layer = e.target;
    var content = getInfoContent(layer.feature.properties);
    layerPopup = L.popup({
        autoPan: false
    }).setLatLng(e.latlng).setContent(content).openOn(mymap)
}

The problem is that onClick event is not always fired. More exactly, it is fired in about 10% cases. If I cancel popup then it works. Is it possible to solve the problem?

Upvotes: 1

Views: 1013

Answers (1)

ghybs
ghybs

Reputation: 53185

A usual issue is that you open a popup on mouseover at the "mouseover" event position. In the case of a marker, this position is the marker's coordinates, which makes the popup covering the entire marker, hence the mouse is "taken out" of the marker.

Here you do not have a "mouseout" listener, so you may not notice this effect. But the mouse is no longer on your original layer (it is now on your popup), hence the "click" happens on the popup, not on your layer.

Sometimes it may still work, if you accidentally slightly moved your mouse back over the layer, and a new popup is not inserted yet (for whatever reason)

Demo: http://playground-leaflet.rhcloud.com/gusu/1/edit?html,output

2 possible workarounds are:

  • To bind the popup on your original layer, instead of opening it on the map at the "mouseover" exact position. That way, it opens above the marker, or centered on the path.
  • To use a Tooltip instead of a popup, which is more adapted to "mouseover" effect.

Example: http://playground-leaflet.rhcloud.com/zado/1/edit?html,output

Upvotes: 2

Related Questions