I would like to highlight different areas on a map when the mouse hovers over the legend using leaflet.

This jsfiddle http://jsfiddle.net/expedio/3w4j2u9z/ is probably the closest to what I am looking for, however, with my limited knowledge of JS and Leaflet I'm struggling to figure out how to link the hover to multiple ID's.

I've searched the internet far and wide and can't seem to find a solution.

Here is an example of the final outcome we would like to achieve - http://atlas.id.com.au/adelaide#MapNo=10173&SexKey=3&datatype=1&themtype=3&topicAlias=population-density&year=2011

1 Answer 1


There is no special difficulty in implementing what you describe.

The idea is to add event listeners on your legend items.

On "mouseover", loop through all shapes and compare their property (here, density) to the range of your legend item, and highlight if it matches.

On "mouseout", reset all shapes style.

var legend = L.control({
  position: 'topright'

legend.onAdd = function(map) {
  var div = L.DomUtil.create('div', 'info legend'),
    grades = [0, 10, 20, 50, 100, 200, 500, 1000],
    from, to, span, color, text;

  for (var i = 0; i < grades.length; i++) {
    from = grades[i]; // Zahlen setzen 
    to = grades[i + 1];

    span = document.createElement("span");
    span.dataset.from = from;
    span.dataset.to = to;

    color = document.createElement("i");
    color.style.background = getColor(from + 1);

    text = document.createTextNode(from + (to ? '-' + to : '+'));


    span.addEventListener("mouseover", function (event) {
      var span = event.currentTarget,
        from = span.dataset.from,
        to = span.dataset.to,
        above = to === "undefined";

      geojson.eachLayer(function (layer) {
        var density = layer.feature.properties.density;
        if (density >= from && (above || density < to)) {
    span.addEventListener("mouseout", function () {


  return div;


Updated JSFiddle: http://jsfiddle.net/3w4j2u9z/23/

  • 1
    You are welcome. Please note that the Stack Exchange way of thanking people is also to accept the answer that helped you. It also tells the community that your question is solved.
    – ghybs
    Commented Aug 13, 2016 at 9:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.