Programmatically collapse Leaflet JS layer control

controls, javascript, layer, leaflet

Solution

The state of this control is controlled by the `leaflet-control-layers-expanded` class. If you add or remove this class to the `leaflet-control-layers` element, then you can control the state.

These examples use jQuery for simplicity.

To expand the control:

$(".leaflet-control-layers").addClass("leaflet-control-layers-expanded")

To collapse the control:

$(".leaflet-control-layers").removeClass("leaflet-control-layers-expanded")

Problem

How can the Leaflet JS layer control be closed using JS code? On desktop, the control closes nicely when the mouse cursor leaves the control. However, on mobile phones, the user needs to tap outside the control to close it. I would like to manually close it once a user selects a layer inside the control.

Original source