prime90
prime90

Reputation: 959

Toggle leaflet legend on/off via eventListener

I'm trying to go for an on/off toggle when "Legend" is clicked in the navbar. However, when I'm constructing the function for addEventListener, I keep receiving a type error. I understand this is because info is not defined but I'm not sure how to define it so the style display can be changed to block and it will appear on the map when Legend is clicked in the nav bar.

Any suggestions to point me in the right direction?

HTML:

<!--Navbar-->
    <nav class="navbar">
        <div class="logo">
            <h4> Earthquake Feed</h4>
        </div>
        <ul class="nav-links">
            <li><a href="#simpleModal" id="aboutModal">About</a></li>
            <li><a href="#legend" id="legend">Legend</a></li>
        </ul>
    </nav>

CSS:

/*CSS for legend*/
.info {
  padding: 6px 8px;
  font: 14px/16px Arial, Helvetica, sans-serif;
  background: white;
  background: rgba(255,255,255,0.8);
  box-shadow: 0 0 15px rgba(0,0,0,0.2);
  border-radius: 5px;
  display: none;
  }

.legend {
  background-color: “black”;
  line-height: 26px;
  color: #555;
  width: auto;

Javascript:

// adds legend to map
var legend = L.control({position: 'bottomright'});

legend.onAdd = function(map) {
    var div = L.DomUtil.create('div', 'info legend'),
        magnitudes = [0,1,2,3,4,5];

    div.innerHTML += "<h4 style='margin:5px'>Magnitude</h4>" 
    div.innerHTML += '<i class="circleR" style=background:>' + '</i>' + "Recent" + '<br>'

    // loop through color intervals and generate a lable
    for (var i=0; i < magnitudes.length; i++) {
        div.innerHTML += 
                        '<i class="circle" style=background:' + getColor(magnitudes[i] + 1) + '></i>' +
                        magnitudes[i] + (magnitudes[i+1]?'&ndash;' + magnitudes[i+1] + '<br>': '+');
    }
    return div;
};
legend.addTo(map);

// toggles legend on and off
var legendLink = document.getElementById("legend");
legendLink.addEventListener('click', openLegend);
function openLegend(){
    info.style.display = 'block';
}

Upvotes: 0

Views: 718

Answers (1)

peeebeee
peeebeee

Reputation: 2618

You need a DOM element that specifies the element you want to style.

function openLegend(){
    document.getElementByClass("legend").style.display = 'block';
}

should work for you.

Upvotes: 1

Related Questions