Overlay div over leaflet and stop mouse action propagation

Viewed 2159

How would I stop the propagation of clicking and scrolling on a div, overlaying a leaflet map? That seems to be very tricky... Something like

customPreventDefault(e) {
    e = e || window.event;
    if (e.preventDefault)
        e.preventDefault();
    e.returnValue = false;
}

document.getElementById('no-scrolling-clicking').onmousewheel =
    function (e) {
        document.getElementById('prevent-scrolling').scrollTop -= e.wheelDeltaY;
        customPreventDefault(e);
    }
}

doesn't do anyhting. It needs to work in IE as well...

http://jsfiddle.net/LnzN2/4888/

3 Answers

Move your parent-div outside of the map div.

Change your HTML to:

<div 
  id="map">

</div>
<div 
  id='parent-div'
  class='some-div'>
   I am the parent! Like the leaflet map, I don't want the mouse events clicking/scrolling bubbling onto me neither.
    <div 
      class='some-div'
      id='no-scrolling-clicking'>
      Stop Scrolling and clicking Event in me! Stop Scrolling and clicking Event in me! Stop Scrolling and clicking Event in me! Stop Scrolling and clicking Event in me! Stop Scrolling and clicking Event in me! Stop Scrolling and clicking Event in me! Stop Scrolling and clicking Event in me! Stop Scrolling and clicking Event in me! Stop Scrolling and clicking Event in me! Stop Scrolling and clicking Event in me!
    </div>
  </div>

You can take advantage of Leaflet built-in L.DomEvent.disableScrollPropagation(element) utility function to prevent the scroll on your custom elements from propagating to the underlying map.

var el = document.getElementById('no-scrolling-clicking');
L.DomEvent.disableScrollPropagation(el);

Updated JSFiddle: http://jsfiddle.net/LnzN2/4929/

Although this function is not mentioned in the docs for Leaflet 0.7.x, it is already available.

It takes care of browser variants for you.

Note that you should consider upgrading to Leaflet 1+ (current stable version is 1.3.4).

leaflet offers a functionality for this.

  var div = L.DomUtil.get('no-scrolling-clicking');
  L.DomEvent.on(div, 'mousewheel', L.DomEvent.stopPropagation);
  L.DomEvent.on(div, 'click', L.DomEvent.stopPropagation);
Related