0

I want to hide a circle that is attached to the cursor when the cursor leaves the map. This circle must also hide when the cursor enters a ol.control. In older OL versions I simply added a mouseleave listener to the canvas object, but in OL6 it is not guaranteed that a canvas exists and the propagation of those basic events seem to be stopped for all elements below ol-viewport.

How can I achieve this behavior in OL6?

anste
  • 118
  • 1
  • 3
  • 11
  • When listening for contextmenu events I replaced the canvas by `map.getViewport().getElementsByClassName('ol-overlaycontainer-stopevent')[0]` However in your case it might be easier to use `map.on('pointermove', ...)` and check if `event.pixel` is at the edge of the map. – Mike Jan 09 '20 at 10:51
  • But this way I can't detect if the cursor leaves by hovering a ol.control. – anste Jan 09 '20 at 12:22

1 Answers1

0

You will need separate listeners for the controls. My code for a context menu (not active on controls) looks like

var controlOver = false;

function setControlOver(element) {
    element.addEventListener('mouseover', function() { controlOver = true; });
    element.addEventListener('mouseout', function() { controlOver = false; });
}

setTimeout(function() {
    var controls = map.getViewport().getElementsByClassName('ol-control');
    for (var i=0; i<controls.length; i++) {
        setControlOver(controls[i]);
    }
    map.getControls().on('add', function(e) {
        // ????? setControlOver(e.element.getElement());
    });
}, 250);

map.getOverlays().on('add', function(e) {
    setControlOver(e.element.getElement());
});

var canvas = map.getViewport().getElementsByClassName('ol-overlaycontainer-stopevent')[0];

canvas.addEventListener('contextmenu', function (e) {
    if (!controlOver) {
        e.preventDefault();
        openContextMenu(e.x, e.y);
    }
});
Mike
  • 16,042
  • 2
  • 14
  • 30
  • Thank you for your answer. This gets more complicated when controls are added or removed over time. Another problem since OL6 is that I don't get any events on elements below ol-viewport. – anste Jan 10 '20 at 14:50
  • I have a similar problem with overlays but for simplicity didn't include that here. I added new listeners as the collection was updated, and that code is now in the example. You could perhaps do something similar to new controls, but I'm not sure how to get the element for an indivual control. – Mike Jan 10 '20 at 15:14