Disable panning/dragging on leaflet map for div within map

Using the example from the Leaflet website, note where the L.Control object is instantiated as info; this is the <div> box in the upper-right associated with the map's hover interaction. Here is where it is defined in index.html from the Leaflet example:

    // control that shows state info on hover
    var info = L.control();

    info.onAdd = function (map) {
        this._div = L.DomUtil.create('div', 'info');
        this.update();
        return this._div;
    };

    info.update = function (props) {
        this._div.innerHTML = '<h4>US Population Density</h4>' +  (props ?
            '<b>' + props.name + '</b><br />' + props.density + ' people / mi<sup>2</sup>'
            : 'Hover over a state');
    };

    info.addTo(map);

To disable the dragging when a user's cursor is inside this <div> box, add an event listener to the HTMLElement (a <div> element) that contains the L.Control object:

    // Disable dragging when user's cursor enters the element
    info.getContainer().addEventListener('mouseover', function () {
        map.dragging.disable();
    });

    // Re-enable dragging when user's cursor leaves the element
    info.getContainer().addEventListener('mouseout', function () {
        map.dragging.enable();
    });

Recall that map was defined as the L.Map instance earlier.


An alternative solution to that is to stop event propagation with JavaScript (like it's done for Leaflet controls, e.g. zoom buttons):

var div = L.DomUtil.get('div_id');
if (!L.Browser.touch) {
    L.DomEvent.disableClickPropagation(div);
    L.DomEvent.on(div, 'mousewheel', L.DomEvent.stopPropagation);
} else {
    L.DomEvent.on(div, 'click', L.DomEvent.stopPropagation);
}

A small optimization for the solution from @Arthur. Use mousedown and mouseup. So it didn't trigger when you just drag over your div. Only when you start dragging inside your div.

Attention use mouseup for the whole html

$('.yourDiv').mousedown( function() {
    map.dragging.disable();
});

$('html').mouseup( function() {
    map.dragging.enable();
});

Tags:

Leaflet