How to prevent leaflet map elements to get focus

Viewed 2078

I have a form and inside the form is a leaflet map. I want to move between elements pressing tab key and I do not want the map or his elements ( buttons ,markers,etc) to get focus. How can I add tabindex="-1" to maps controls and elements to prevent focus, or what I can do to prevent focus?

Here is a jsfiddle to show my scenario: http://jsfiddle.net/kedar2a/LnzN2/2/

var osmUrl = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png', osmAttrib = '&copy; <a ref="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors',
       osm = L.tileLayer(osmUrl, {attribution: osmAttrib  });

var map = L.map('map').setView([19.04469, 72.9258], 12).addLayer(osm);

var marker = L.marker([19.04469, 72.9258]).addTo(map);
#map {
    height: 150px;
    width: 300px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.5.1/leaflet.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.5.1/leaflet.js"></script>
<input type="text" autofocus />
<div id="map"></div>
<input type="text"  />

1 Answers

There is no one-shot solution but you can achieve this by disabling each map element in three steps:

  1. Disable focus for markers: Disable keyboard support for markers by adding keyboard:false to the marker element.

  2. Add tabIndex="-1" attribute to all <a> elements located inside .leaflet-control divs

    var elements = document.querySelectorAll(".leaflet-control a");
    for (var i = 0; i < elements.length; ++i) {
      elements[i].setAttribute("tabindex", "-1");
    }
    
  3. Disable focus for Close Button inside any open marker popup.

      var marker = L.marker(e.latlng, {
          draggable: true,
          keyboard: false,
          title: "Resource location",
          alt: "Resource Location",
          riseOnHover: true
        }).addTo(map)
        .bindPopup(e.latlng.toString()).on('popupopen',
          function(popup) {
            //disable focus of close button
            var elCloseButton = document.getElementsByClassName("leaflet-popup-close-button")[0];
            elCloseButton.setAttribute("tabindex", "-1");
          }).openPopup();
    

See my implementation: http://jsfiddle.net/trkaplan/bv763tkf/

Related