Search code examples
javascriptjqueryleafletmouseout

Leaflet on mouseout event not firing when changing iconUrl


I am experiencing an issue with leaflet and it's mouseout event.

In the code below, sometimes (particulary if you move the mouse fast), the mouseout event is not triggered. The Mouse out ! doesn't appear in the console.

I found out that this behaviour is related to the icon replacement. A simple layer.setStyle works every time. (Here I use the leaflet-gpx plugin but it works the same way as leaflet's IconUrl or shadowUrl)

// This works every time
gpxPath.on('mouseover', function (e) {
    var layer = e.target;
    layer.options.marker_options.startIconUrl = 'myHoverIconStartUrl';
    layer.options.marker_options.endIconUrl = 'myHoverIconEndUrl';
    layer.reload();
});

gpxPath.on('mouseout', function (e) {
    console.log('Mouse out !')
    var layer = e.target;
    /* those two lines below cause the issue */
    layer.options.marker_options.startIconUrl = '';
    layer.options.marker_options.endIconUrl = '';
    layer.reload();
});

I know that the mouseout event sometimes causes issues like this one, but in this particular case I am forced to use the leaflet events and I am a little bit out of ideas.


Solution

  • Are you trying to make markers display a different icon on hover?

    It's hard to tell without an example, but what I think is happening is:

    Your mouseoutevent isn't getting triggered reliably because the mouseover event is ran continuously, as long as your mouse is positioned on it, every time the icons rebuild.

    You may notice this if you add a console.log in that function as well. You can happen to move off while it is rebuilding, so you don't trigger the mouseout event reliably.

    If so, try something like:

    line.once('mouseover', function () {
        //switch to icons
    
    });
    
    line.on('mouseout', function () {
        //clear icons
        
        //Prevent mouseover event from firing continuously if/when the icon changes
        line.once('mouseover', function () {
            //switch to icons
        });
    });